I have a view in my project it has a kendo dropdownlistfor
#(Html.Kendo().DropDownListFor(m => m.database_pk)
.BindTo(Model.databases)
.Name("database_pk").OptionLabel("Select one...")
.DataValueField("Value")
.DataTextField("Text")
.HtmlAttributes(new { #id = "database_pk", onchange = "changeDatabase()" })
)
and a kendo tabstrip
#(Html.Kendo().TabStrip()
.Name("menu")
.Items(items =>
{
items.Add().Text("Database Info").LoadContentFrom("DatabaseInfo", "Home", new { database_pk = Model.database_pk }).Selected(true);
items.Add().Text("Tables").LoadContentFrom("TableInfo", "Table", new { database_pk = Model.database_pk }).Selected(true);
items.Add().Text("Entities").LoadContentFrom("EntityInfo", "Entity", new { database_pk = Model.database_pk }).Selected(true);
})
.Events(events =>
{
events.Select("selectMenuTabs");
})
)
The deal is I need my tabstrip to "reload" the selected tab if the onchange event is fired on the dropdownlist
The function for onchange is
function changeDatabase() {
var selected_pk = $('#database_pk').val();
reloadTabstrip();
}
and teh reload function is
function reloadTabstrip() {
var tabStrip = $("#menu").data("kendoTabStrip");
tabStrip.reload($(".item", tabStrip.element)[0]);
}
the reloadTabstrip function is not working and I'm having a hard time finding anything on the web to point me in the right direction.
solved teh problem with the following jquery script
function reloadTabstripItem() {
var selected_pk = $('#database_pk').val();
var index = $("#menu").data("kendoTabStrip").select().index();
switch (index) {
case 0:
actionurl = "/Home/DatabaseInfo";
break;
case 1:
actionurl = "/Table/TableInfo";
break;
case 2:
actionurl = "/Entity/EntityInfo";
break;
}
$.ajax({
url: "/Home/DatabaseInfo",
type: 'GET',
data: { database_pk: selected_pk }
}).done(function (html) {
$($("#menu").data("kendoTabStrip").contentElement(0)).html(html);
});
}
Related
Hello everyone im just simply trying to load values in a dropdownlist from a controller if I have both the value and text be the same values it works with the model property. But im trying to have the value be the id and the text to be the name with this setup the dropdown is not loading the id.
If both text and value are the same I can just do this and it works
vm.CustomerName = model.CustomerName;
View DDL
#Html.DropDownListFor(e => e.ServiceVM.Employee, Model.Employees, "Select Employee", new { #class = "form-control" })
Some of what i tried.
vm.Employee = new SelectListItem { Value = model.EmployeeID.ToString(), Selected=true };
//vm.EmployeeName = model.EmployeeID.ToString();
//var employee = new Employee_Main();
//try
//{
// employee = context.Employee_Main.Where(z => z.EmployeeID == model.EmployeeID).FirstOrDefault();
//}
//catch(System.Exception) { }
//vm.EmpID = employee.EmployeeID.ToString();
//vm.EmployeeName = employee.EmployeeID.ToString();
I really thought this would of worked.. Im setting the correct 'value' and 'text' that are displayed in the list of ddl items. and also saying selected=true.
//vm.EID = model.EmployeeID;
if (model.EmployeeID != null)
{
if(Int32.TryParse(model.EmployeeID.ToString(), out int empID))
{
var employee = context.Employee_Main.Where(e => e.EmployeeID == empID).FirstOrDefault();
if(employee != null)
{
vm.Employee = new SelectListItem() { Value = employee.EmployeeID.ToString(), Text = employee.EFullName, Selected=true };
}
}
#Html.DropDownListFor(e => e.ServiceVM.Employee, Model.Employees, "Select Employee", new { #class = "form-control" })
I got it working.
I forgot to change my javascript to match with the changing model fields.
var employ = modalA.find(body).find("#ServiceVM_Employee");
//empid.val(jsonObject.employeeid);
//empfn.val(jsonObject.employeefname);
//empln.val(jsonObject.employeelname);
//empem.val(jsonObject.employeeemail);
//emppo.val(jsonObject.employeeposition);
//empname.val(jsonObject.employeefullname);
employ.val(jsonObject.employeeid);
Also for adding content to a listbox.
function displayContactData(conID, modal) {
return $.ajax({
url: '#Url.Action("GetContactInfo", "Service")',
data: { contact: conID },
dataType: 'json',
success: function (data) {
var modalX = modal;
var fullL = modalX.find('.modal-body').find('#lstContact');
fullL.empty();
$.each(data, function () {
fullL.append("<option value='" + this.Value + "'>" + this.Text + "</option");
});
}
});
}
So im using jquery.dataTables.js to display about a thousand rows, while only showing about twenty at a time. The problem is with the dropdownlist on every line it takes about 10 seconds to load the page and shows a lot more of the records while loading. I thought about doing it after page load with ajax but not sure how to do that cleanly with all of them. Any ideas.
#for (int i = 0; i < Model.billVersion.Count; i++)
{<tr>
<td>#Html.DisplayFor(model => model.billVersion[i].billNumber)#Html.HiddenFor(model => model.billVersion[i].billNumber)</td>
<td>#Html.DisplayFor(model => model.billVersion[i].lrNumber)</td>
<td>#Html.DisplayFor(model => model.billVersion[i].previousYear)</td>
<td>#Html.DisplayFor(model => model.billVersion[i].committeeRec)</td>
<td>#Html.DropDownListFor(model => model.billVersion[i].committeeID, #Model.committeDropDown, "")</td>
<td>#Html.CheckBoxFor(model => model.billVersion[i].save_Remove)</td>
</tr>
}
An application of Jquery UI autocomplete:
!function ($) {
var cache = {};
$("[data-options]").each(constructAjaxOptions);
function constructAjaxOptions() {
var el = $(this),
acEl = $(el.clone(false)),
url = el.attr('data-options'),
initialLabel = el.attr('data-initial-label') || el.val(),
myCache = cache[url];
if (!myCache) {
myCache = cache[url] = {};
}
el.hide();
acEl
.removeAttr('id').removeAttr('name')
.val(initialLabel)
.insertAfter(el)
.autocomplete({
autoFocus: true,
minLength: 0,
source: function (request, response) {
var term = request.term;
if (term in myCache) {
response(myCache[term]);
return;
}
$.getJSON(url, request, function (data, status, xhr) {
myCache[term] = data;
response(data);
});
},
focus: function (event, ui) {
// Overridden to keep the value of the field
// from flashing in the textbox.
return false;
},
select: function (event, ui) {
acEl.val(ui.item.label);
el.val(ui.item.value);
return false;
}
});
}
}(jQuery);
.cshtml
<input type="text" id="#Html.IdFor(model => model.billVersion[i].committeeID)" name="#Html.NameFor(model => model.billVersion[i].committeeID)" value="#Value"
data-options="#Url.Action("BillVersions", "Options")" data-initial-label="#model => model.billVersion[i].commiteeName" />
Within an MVC action:
var model = billVersions.Select(o => new
{
value = o.committeeID,
label = o.commiteeName
})
.ToList();
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = model };
I am very new to MVC, and am try to set up a series of cascading drop down lists using this example.
But I am stuck a little bit, because I don't know how to get the value from the second drop down and send it to controller when I press the appropriate button.
Here is my view:
<script type="text/javascript">
$('#list').change(function() {
var selectedClient = $(this).val();
if (selectedClient != null && selectedClient != '') {
$.getJSON('#Url.Action("SelectC")', { clientID: selectedClient }, function (client) {
var campaingSelect = $('#clist');
campaingSelect.empty();
$.each(client, function(index, clients) {
campaingSelect.append($('<option/>', {
value: clients.value,
text: clients.text
}));
});
});
}
});
</script>
#using (Html.BeginForm("CreateNewCampaign", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.alreadyCreatedCampaignName, "Name:")
#Html.DropDownList("clist","-- Select Client -2-")
<input type="Submit" name="button" value="Select" class="btn btn-primary" />
}
Controller:
public ActionResult SelectC(int clientId, CampaignModel model, FormCollection form)
{
Session["ClientID"] = clientId;
ViewBag.ClientName = "You're using: " + Session["ClientName"];
var CampaignInf = CampaignManagementService.GetCampaigns((string) Session["ticket"], clientId);
List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>();
foreach (var element in CampaignInf)
{
itemas.Add(new AlreadyCreatedCampaignList() {CampId = element.Key, CampName = element.Value});
}
var listOfCam = new SelectList(itemas, "campID", "campName", 1);
return Json(listOfCam.Select(x => new {value = x.Value, text = x.Text}), JsonRequestBehavior.AllowGet);
}
I want to get the value to other controller, and I am not sure of the right way to go about doing this.
You can get value of dropdownlist just by giving it ID and call $("#id").val();, then you can transfer it to the controller through ajax maybe.
Here is mine, try it
public ActionResult ActionName(string dropdown_value){
//your code
}
<script>
$(document).ready(function(){
$("submit").click(function(){
$.ajax({
url:"Controller/ActionName",
datatype: "POST",
data: { dropdown_value : $("#clist").val() },
success : function(){ //your code if success }
});
});
});
</script>
I'm creating my own filter. The filter has a dropdownlist, when this dropdownlist changes jquery will make an ajaxcall to the corresponding HTTPPOST - controller action. In this action I filter the list and pass it through to my view.
Once the list has reached my view, the webgrid is not updating. Here is some code with some debug information to show what's happening.
Controller
normal action
public ActionResult Projects()
{
IEnumerable<Project> projects = Adapter.ProjectRepository.Get();
int test = projects.Count();
List<ProjectsDisplayViewmodel> projectsView = new List<ProjectsDisplayViewmodel>();
string strCats = "";
foreach (Project prj in projects)
{
strCats = "";
Mapper.CreateMap<Project, ProjectsDisplayViewmodel>();
ProjectsDisplayViewmodel newProject = Mapper.Map<Project, ProjectsDisplayViewmodel>(prj);
foreach (Category cat in prj.Categories)
{
strCats += cat.CategoryName + ", ";
}
newProject.strCategories = strCats;
projectsView.Add(newProject);
}
ViewBag.Categories = new SelectList(Adapter.CategoryRepository.Get(), "CategoryID", "CategoryName");
/*projectsview contains 4 projects now*/
return View(projectsView);
}
httppost action
[HttpPost]
public ActionResult Projects(string catID, string strSearch)
{
IEnumerable<Project> projects = Adapter.ProjectRepository
.Get()
.Where(x =>
x.Categories.Any(
c =>
c.CategoryID == Convert.ToInt16(19))
);
int test = projects.Count();
List<ProjectsDisplayViewmodel> projectsView = new List<ProjectsDisplayViewmodel>();
string strCats = "";
foreach (Project prj in projects)
{
strCats = "";
Mapper.CreateMap<Project, ProjectsDisplayViewmodel>();
ProjectsDisplayViewmodel newProject = Mapper.Map<Project, ProjectsDisplayViewmodel>(prj);
foreach (Category cat in prj.Categories)
{
strCats += cat.CategoryName + ", ";
}
newProject.strCategories = strCats;
projectsView.Add(newProject);
}
ViewBag.Categories = new SelectList(Adapter.CategoryRepository.Get(), "CategoryID", "CategoryName");
/*projectsview contains 1 project now AND WILL DISPLAY 4*/
return View(projectsView);
}
project.cshtml
#model IEnumerable<Freelauncher.Models.ProjectsDisplayViewmodel>
#{
ViewBag.Title = "Projects";
}
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 25,
selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);
}
<h2>Alle projecten</h2>
#Html.DropDownList("Categories", (SelectList) ViewBag.Categories)
<div id="gridContent">
#grid.GetHtml(
columns: grid.Columns(
grid.Column("ProjectTitle", "Titel"),
grid.Column("ProjectDeadlineDate", "project deadline"),
grid.Column("ProjectEndRegisterDate", "Registreer deadline"),
grid.Column("ProjectBudget", "Prijs"),
grid.Column("ProjectIsFixedPrice", "Vaste prijs"),
grid.Column("strCategories","Categorieën"),
grid.Column("ProjectID", "meer info", format: (item) => Html.ActionLink("info", "project", new { Id = item.ProjectID} ))
//grid.Column("ProjectID", "meer info", format: Html.ActionLink("info", "project", new { Id = }
))
</div>
What am I missing that the project list in my view is not updated, the correct data is passed to the view....
edit
The ajax call
$("#Categories").change(function () {
var param = $(this).val();
$.ajax({
type: "POST",
url: "/Project/Projects",
data: { catID: $(this).val(), strSearch: 'test' },
dataType: "json",
success: function (response) { console.log("succes"); },
error: function (xhr, ajaxOptions, thrownError) {console.log("error"); }
});
});
I just noticed that nothing is printed in my console.log.... Not the success neither the error function.
You don't seem to be doing anything in the success callback of your AJAX request (other than a console.log call). So it's perfectly normal that nothing updates. You need to manually update your DOM if you want this to happen.
So you should modify your HttpPost controller action so that it returns a PartialView containing the grid. And then in your success callback inject the newly received partial into the DOM:
success: function (response) {
$('#some_id_of_a_containing_div').html(response);
console.log("succes");
},
In this example you should wrap the partial view into a containing div which will get updated here:
<div id="some_id_of_a_containing_div">
#Html.Partial("Partial_Containing_Your_Grid")
</div>
i have a coded a radio button in MVC razor.below is the code for it.
#{
var LinkRadioName = "_Link";
var ContentRadioName ="_Content";
var TextRadioName = "_Text";
var ExternalLinkRadioName ="_ExternalLink";
var FilelistRadioName ="_Filelist";
#Html.RadioButtonFor(m => m.MenuType, true, new { #id = LinkRadioName })
#Html.Label("Link")
#Html.RadioButtonFor(m => m.MenuType, false, new { #id = ContentRadioName })
#Html.Label("Content")
#Html.RadioButtonFor(m => m.MenuType, true, new { #id = TextRadioName })
#Html.Label("Text")
#Html.RadioButtonFor(m => m.MenuType, false, new { #id = ExternalLinkRadioName })
#Html.Label("External Link")
#Html.RadioButtonFor(m => m.MenuType, true, new { #id = FilelistRadioName })
#Html.Label("File List")
}
can any one help me ,as to how can i access this radiobutton set in jquery:
i have a code like this
#Html.RadioButton("TypeOfmenu", 1)Link
#Html.RadioButton("TypeOfmenu", 2)Content
#Html.RadioButton("TypeOfmenu", 3)Text
#Html.RadioButton("TypeOfmenu", 4)ExternalLink
#Html.RadioButton("TypeOfmenu", 5)Filelist
and i access it very easily in jquery like
$("input[name$='TypeOfmenu']").click(function () {
var Selectedvalue = $(this).val();
});
is there any way to access the #Html.RadioButtonFor control in d same way like
$("input[name$='MenuType']").click(function () {
var Selectedvalue = $(this).val();
});
??????
please help me as i m very new in MVC as well as jquery.
Since you are accessing the values in your function with this.val(), you can just bind your event to all radio buttons
$(":radio").click(function () {
var Selectedvalue = $(this).val();
//OR
//var Selectedvalue = this.value;
});