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;
});
Related
I have two drop down list and I've populate them like this :
private List<Client> Client()
{
var allClients= _db.tboClient.Select(x =>
new Tecnico
{
Id = x.Id,
Nome = x.Nome
}).ToList();
return allClients;
}
private List<Pricerice> Price()
{
var allPrice = _db.tboPrice.Select(x =>
new Cliente
{
Id = x.Id,
Nome_azienda = x.Nome_azienda
}).ToList();
return allPrice ;
}
And then some methods that I recall Client() and Price(). I load the View like this :
public IActionResult Create()
{
ViewBag.Price= Pricei();
ViewBag.Clienti = CLienti();
return View();
}
This is the HTML:
<div class="dropdown">
#Html.DropDownListFor(m => m.CLienti, new SelectList(ViewBag.CLienti, "Id", "Nome_azienda"), new { #id = "ddlCLienti", #class = "btn btn-primary dropdown-toggle mr-3" })
</div>
<div class="dropdown">
#Html.DropDownListFor(m => m.Price, new SelectList(ViewBag.Price, "Id", "Nome"), new { #id = "ddlClienti", #class = "btn btn-primary dropdown-toggle mr-3" })
</div>
I want to populate the second(Price) drop down list based on the value selected from the first drop down list.
I want to populate the second(Price) drop down list based on the value selected from the first drop down list.
To achieve above requirement of implement a cascading dropdown, you can try to populate the second dropdown based on the previous selection of the first dropdown on "ddlCLienti" dorpdown change event, like below.
<script>
$(function () {
$("select#ddlCLienti").change(function () {
var CLienti = $(this).val();
$("select#ddlPrice").empty();
$.getJSON(`/your_controller_name_here/GetPriceBySelectedCLienti?CLienti=${CLienti}`, function (data) {
//console.log(data);
$.each(data, function (i, item) {
$("select#ddlPrice").append(`<option value="${item.id}">${item.nome}</option>`);
});
});
})
})
</script>
GetPriceBySelectedCLienti action method
public List<Price> GetPriceBySelectedCLienti(int CLienti)
{
//query data based on selected CLienti
//...
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");
});
}
});
}
Controller Json result
public JsonResult GetStaffJson( string Branch)
{
List<SelectListItem> S_li = new List<SelectListItem>();
try
{
TempData["Staff_List"] =S_li = cmnclass.Get_staff_SelectList(Branch);
}
catch (Exception ex)
{
logger.LogError(ex);
}
finally
{
}
return Json(S_li, JsonRequestBehavior.AllowGet);
}
View
#Html.DropDownListFor(m => m.clsAUDIT.Branch, ViewBag.Branch_list as IEnumerable<SelectListItem>,"Select a Branch", new {#id="ddlBranch", #class = "form-control", #actor = "DropDown" })
And
#Html.DropDownListFor(m=>m.clsCGT.fo_Name_CGT, TempData["Staff_List"] as IEnumerable<SelectListItem> , new {#id="ddl_CGT_fo",#class="input-sm", #actor = "DropDown", #style = "width:auto;" })
Two more
#Html.DropDownListFor(m => m.clsGRT.GRT_fo_Name, TempData["Staff_List"] as IEnumerable<SelectListItem>, new {#id="ddl_GRT_fo", #class = "input-sm", #actor = "DropDown", #style = "width:auto;" })
#Html.DropDownListFor(m => m.clsGRT.GRT_bm_name, TempData["Staff_List"] as IEnumerable<SelectListItem>, new { #id = "ddl_GRT_bm", #class = "input-sm", #actor = "DropDown", #style = "width:auto;" })
Now Jquery
$('#ddlBranch').change(function () {
var url = '#Url.Action("GetStaffJson", "Annex1")';
var Branch = $("#ddlBranch").val();
var ddl_CGT_fo = $("#ddl_CGT_fo");
var ddl_GRT_fo = $("#ddl_GRT_fo");
var ddl_GRT_bm = $("#ddl_GRT_bm");
$.getJSON(url, { Branch: Branch }, function (response) {
ddl_CGT_fo.empty();
ddl_GRT_fo.empty();
ddl_GRT_bm.empty();
debugger;
$.each(response, function (index, item) {
debugger;
var p = new Option(item.Text, item.Value);
ddl_CGT_fo.append(p);
ddl_GRT_fo.append(p);
ddl_GRT_bm.append(p);
});
});
});
On change of ddlBranch I am populating three DropDownList's
ddl_CGT_fo
ddl_GRT_fo
ddl_GRT_bm
Its working fine but only populating last DropDownList ' ddl_GRT_bm' ,
What I am missing here ? why first two DropDownList Still empty ?
You should use the .clone() function for the new created option while appending it.
var p = new Option(item.Text, item.Value);
ddl_CGT_fo.append($(p).clone());
ddl_GRT_fo.append($(p).clone());
ddl_GRT_bm.append($(p).clone());
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);
});
}
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 };