how to fill 2nd combobox with asp.net mvc ajax - c#

I am using aspnet MVC 5 in Visual Studio 2014.1
I have a combobox that is filled with data from the database:
ViewBag.Brans = new SelectList(db.Brans.OrderBy(m => m.Ad), "No", "Ad");
#Html.DropDownList("Brans", null, htmlAttributes: new { #class = "form-control" })
Then i have another combobox. and i want to fill that combobox after i select an option from first combo.
Its like selecting country from the first combo. then cities will appear in the second one.
Does any of you know how to do this?

One of the options is to to make Ajax request to action which will return your list items
public virtual JsonResult GetCountryStates()
{
return Json(
new
{
new List<SelectListItem>() {YOUR ITEMS HERE}
});
}
Then in your Ajax callback body put code like that
function (data) {
//var selValue;
data = $.map(data, function (item, a) {
if (item.Selected) {
selValue = item.Value;
}
return "<option value=\"" + item.Value + "\" " + (item.Selected ? "selected" : "") + ">" + item.Text + "</option>";
});
$('statesSelect').html(data.join(""));
$('statesSelect').val(selValue);
},

#fly_ua : Good way of populating depending dropdown
But what if we post form and on selected value we fetch next dropdown data from our controller and again reload the form? This might be the secure way rather than doing AJAX call.

$('##Html.Encode(Html.IdFor(x => x.YourProperty))')on("Change", function (event) {
event.preventDefault();
var id = $(this).val();
$.ajax({
url: '#Url.Action("ActionName", "ControllerName")',
type: "GET",
data: {
id: id,
},
success: function (result) {
$('##Html.Encode(Html.IdFor(x => x.SecondDropDownProperty))').html(result)
}
});
});
create one view with dropdown and rendor razor JSON with this view
By doing this you will create generic dependent dropdown list.

Related

ASP.NET Telerik combobox is not being updated with new values

I have an ASP.NET MVC application which uses Telerik controls. I am new in Telerik controls.
In my asp.net view (.cshtml) I have below Telerik combobox defined:
<div class="inline-form-field">
<label>#Ubicaciones.lblTipoVia.ToUpper()</label>
#(Html.Telerik().DropDownListFor(t => t.tipoViaId)
.BindTo(new SelectList(#ViewBag.tiposVia, "tipoViaId", "descripcion"))
.HtmlAttributes(new { style = "width: 190px;" })
)
</div>
Later in the same view, when a condition is satisfied I call below below javascript function in order to update the combox with new values coming from a function in ASP.NET MVC controller:
function cargarTiposVia(){
var comboTiposVia = $('#tipoViaId').data('tDropDownList').value();
var actionUrl = '#Url.Action("GetTiposVia", "Ubicaciones")?municipioId=' + $('#codigoMunicipio').val() + '&localidadId=' + $('#codigoLocalidad').val() ;
$.ajax({
url: actionUrl,
async:false,
type: "POST",
traditional: true,
success: function (data) {
if (data)
{
comboTiposVia.dataBind(data);
}
}
});
}
Below the function GetTiposVia in the ASP.NET MVC Controller:
public JsonResult GetTiposVia(string municipioId, string localidadId)
{
CommonManager commonManager = new CommonManager(currentUserSociedadId);
List<My.DTOs.TipoViaDTO> tiposVia = commonManager.getTiposViaByMunicipio(municipioId);
//ViewBag.tiposVia = tiposVia;
return Json(new SelectList(tiposVia, "tipoViaId", "descripcion"), JsonRequestBehavior.AllowGet);
}
Ajax result is success (I have checked by putting an alert), so comboTiposVia.dataBind(data) is executed but combox is not loaded with the new values. I do not understand what is happening...
I have solved. The problem was I was taken the current item selected value in the combobox and not the combobox instance.
Changing:
var comboTiposVia = $('#tipoViaId').data('tDropDownList').value();
by
var comboTiposVia = $('#tipoViaId').data('tDropDownList');
is working.

How to convert Kendo dropdownlist into Kendo multiselect

I am converting Kendo dropdownlist from the existing code into Kendo multiselect.
Role Code: Currently Dropdownlist (converting to Kendo multiselect).
I am not getting the correct output.
I have the following code:
<div class="col-md-4 form-group">
#Html.LabelFor(model => model.RoleCode, htmlAttributes: new { }) <span style="color: Red">*</span>
<select id="DDRolecode" multiple="multiple" data-placeholder="Select attendees...">
</select>
</div>
...
...
var url = '#Url.Action("GetRoleCode", "FlowGenerator")';
url = url + '?FlowID=' + flowid + '&RegID=' + RegId;
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
success: function (result) {
debugger;
//$("#DDRolecode").kendoDropDownList({
// dataTextField: "Name",
// dataValueField: "ID",
// optionLabel: "Select",
// dataSource: result
//});
$("#DDRolecode").kendoMultiSelect({
dataTextField: "Name",
dataValueField: "ID",
dataSource: result,
});
var selectedData = [];
for (var i = 0; i < result.length; i++) {
selectedData.push({
text: result[i].Name,
value: result[i].ID
})
}
DDRoleCode.dataSource.data(selectedData);
//DDRoleCode.setDataSource(selectedData);
DDRoleCode.value('');
DDRoleCode.enable(true);
},
error: function (data) {
debugger;
var itemRow = "<ul id='listError'><li>" + "Data Not Bind" + "</li></ul>";
FUNMessageBox(itemRow, "E", 0, 0, "", "");
// alert("error");
}
});
The below is the controller code where I am getting the role codes:
public JsonResult GetRoleCode(int FlowID,int RegID)
{
IEnumerable<GenericValues1> RoleCode = _repository.Context.Database.SqlQuery<GenericValues1>("PROC_GET_ROLECODE #DATA_FLOW_ID={0},#REG_ID={1}", FlowID, RegID).ToList().AsQueryable();
// ViewBag.Tariffs = RoleCode;
return Json(RoleCode, JsonRequestBehavior.AllowGet);
}
As you can see, I tried using the multiselect functionality in the above code. But it didn't work.
To avoid the long comment chain.
From the second image you have provided it looks like the issue of multiple multiselects being added to the same item. This is due to you attaching a a new multiselect control to the same input.
this is a simple fix really.
There are two ways to fix it.
1) Destroy the kendo widget and recreate it
2) Assuming the same structure is used in the underlying datasource and other settings just apply the new datasource data to the widget.
Here is a dojo showing you both examples:
https://dojo.telerik.com/UxetijUy/2
Personally I would go with option 2 as it is a cleaner solution and avoids having to constantly destroy and recreate widgets.
So if you change the required person in the second example it will take a random number of people from the data array for the multiselect and then rebind those options to that control.
So that is all you would have to do with your ajax call is once you have the result just apply the new data to the datasource and then you don't need to keep recreating the widget as you are currently doing.
So in your example:
$("#DDRolecode").data('kendoMultiSelect').value(null);
$("#DDRolecode").data('kendoMultiSelect').dataSource.data(selectedData);
This ensures you have cleared off any selected items before you have attached the new data source.
If you need more info on what is happening. Please ask and I will update my answer accordingly.
The below code worked for me:
$(document).ready(function () {
debugger;
$("#DDRolecode").kendoMultiSelect({
dataTextField: "Name",
dataValueField: "ID",
});
....
....
//go to controller and call Sp and get the result
success: function (result) {
debugger;
var multiSelect = $('#DDRolecode').data("kendoMultiSelect");
multiSelect.value([]);
$("#DDRolecode").data("kendoMultiSelect").setDataSource(new kendo.data.DataSource({ data: result }));
var selectedData = [];
for (var i = 0; i < result.length; i++) {
selectedData.push({
Text: result[i].Name,
Value: result[i].ID
})
}

Problems Cascading dropdownlist, generated dropdown isn't posting selected value to server

Here is my view in image
The code is working fine, but...
When i submit the form, it only sends the value of first dropdownlist (I checked on browser network received arguments), also when i view the page source it doesn't show the generated options that I generated using ajax function.
Here is my Code
Action that generate my first dropdownList
public ActionResult TwoDropDownList()
{
HotelContext H = new HotelContext();
ViewBag.DropDownListOne = new SelectList(H.Continent.ToList(), "Id", "Name");
return View();
}
Action that return json of second dropdownlist data
[HttpPost]
public JsonResult UpdateCountryDropDownList(int ContinentId)
{
HotelContext H = new HotelContext();
List<SelectListItem> CountryNames = new List<SelectListItem>();
List<Country> Co = H.Country.Where(x => x.ContinentId == ContinentId).ToList();
Co.ForEach(x =>
{
CountryNames.Add(new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
});
return Json(CountryNames , JsonRequestBehavior.AllowGet);
}
My Ajax call
#model Hotel.Models.Continent
<script>
$(document).ready(function () {
$("#Name").change(function () {
var ContinentoId = $(this).val();
$.ajax({
type: "POST",
dataType: "json",
data: { ContinentId: ContinentoId },
url: '#Url.Action("UpdateCountryDropDownList","Home")',
success: function (result) {
var Country = "<select id='ddlCountry'>";
Country = Country + '<option value="">--Select--</option>';
for (var i = 0; i < result.length; i++) {
Country = Country + '<option value=' + result[i].Value + '>' + result[i].Text + '</option>';
}
Country = Country + '</select>';
$('#Countries').html(Country);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(arguments)
}
});
});
})
</script>
My View
#using(Html.BeginForm()){
SelectList se = ViewBag.DropDownListOne;
#Html.DropDownListFor(x=>x.Name,se,"--Select--")
<div id ="Countries">
#Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
</div>
<input type="submit" value="submit" style="margin-top:100px;" />
}
HTTPPost Action
[HttpPost]
public string TwoDropDownList(string Name, string ddlCountry)
{
if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(ddlCountry))
{
return ("you must select Both");
}
else
return ("everything is working fine");
}
You already have a <select> element with name="ddlCountry" (generated by #Html.DropDownList("ddlCountry", new List<SelectListItem>(), "--Select--") but in the ajax call, you overwrite it and create a new <select> element without a name attribute (so its value is not posted back.
In the success callback, you should be creating <option> elements and appending them to the existing <select>
success: function (result) {
var country = $('#ddlCountry); // get the existing element
country.empty().append($('<option></option>').val('').text('--Select--'));
$.each(result, function(index, item) {
country.append($('<option></option>').val(item.Value).text(item.Text));
});
}
Side note: Your methods should be returning a collection of anonymous objects, not SelectListItem There is no point sending extra data (the other properties of SelectListItem) across the wire when you don't use them.
I think you are missing the end tag </div> for the <div id ="Countries">.
Try this:
<div id ="Countries">
#Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
</div>

Bind the record to html.dropdownlist using ajax call in mvc

I have one Mvc application. In that application in one View i have 2 #html.dropdownlists.I create one function in <script/> tag, will call at selectedIdnexchange event of first dropdown, and get the selected value and send to controller using ajax call. Controller will return result and trying to bind that result with 2nd dropdown.I want to display all RTO names of selected state in 2nd dropdown.
Here is my dropdown
#Html.DropDownList("State", new List<SelectListItem> {
new SelectListItem{Text="Andaman and Nicobar Islands",Value="Andaman and Nicobar Islands"},
new SelectListItem{Text="Andhra Pradesh",Value="Andhra Pradesh"},
new SelectListItem{Text="Arunachal Pradesh",Value="Arunachal Pradesh"},
new SelectListItem{Text="Assam",Value="Assam"},
new SelectListItem{Text="Bihar",Value="Bihar"},
new SelectListItem{Text="Chandigarh",Value="Chandigarh"},
new SelectListItem{Text="Chhattisgarh",Value="Chhattisgarh"},
new SelectListItem{Text="Dadra and Nagar Haveli",Value="Dadra and Nagar Haveli"},
new SelectListItem{Text="Daman and Diu",Value="Daman and Diu"},
new SelectListItem{Text="National Capital Territory of Delhi",Value="National Capital Territory of Delhi"},
new SelectListItem{Text="Goa",Value="Goa"} }, null, new { #class="ddlHtml form-control",#id="ddlState"})
#Html.DropDownList("RTOListItem", new List<SelectListItem> {
new SelectListItem{Text="None",Value="-1"}
}, null, new { #class = "ddlHtml form-control", #id = "DDlforLocations" })
Here is my script function
$(document).on('change', '#ddlState', function () {
var v = document.getElementById("ddlState");
var statevalue = v.options[v.selectedIndex].text;
alert(statevalue);
var j = v.selectedIndex;
if (j == 0) {
sweetAlert("Oops..", "choose correct State", "error");
}
else {
$.ajax({
url: '#Url.Action("GetLocations","Home")',
type: 'GET',
datatype: 'json',
data: { selectedState: statevalue }
})
.success(function (data) {
$('#DDlforLocations').html(data);
});
}
});
And here is my controller
public JsonResult GetLocations(string selectedState)
{
ConsumerNomineeFormEntities db= new ConsumerNomineeFormEntities();
RTOCode tbl = new RTOCode();
var optionList = db.RTOCodes.Where(a => a.State == selectedState).Select(a => "<option value='" + a.Location + "'>" + a.Location + "</option>");
var val = tbl.Location;
return Json(optionList, JsonRequestBehavior.AllowGet);
}
Please help me. To bind the record returning from controller with 2nd dropdown
It is not good idea to mix the code to build your UI markup in your server side code. You may consider returning some data from your server side which you will use in your client side to build the UI markup.
So let's return a list of SelectListItem objects.
var optionList = db.RTOCodes.Where(a => a.State == selectedState)
.Select(c => new SelectListItem { Value = c.Location,
Text = c.Location}).ToList();
And in your ajax call's success event, loop through this array and build the markup for the options.
success : function(data){
var options="";
// options = "<option value='-1'>None</option>"; // uncomment if you want this item
$.each(data,function(a,b){
options+="<option value='"+b.Value+"'>"+b.Text+"</option>";
});
$("#DDlforLocations").html(options);
}
Also, since you are loading the content of the second dropdown via ajax when user selects something on the first dropdown, you may consider changing that to pure clean HTML
<select name="RTOListItem" id="DDlforLocations">
<option value="-1">Select one</option>
</select>

How to display the value in dropdown using jquery?

i have a dropdown, where i can select AgencyName, with that selected AgencyName, i tried to display its AgentName in the next dropdown. But my code does'nt display the AgentName in the next dropdown.
i have my view page like:
<span class="LabelNormal">Agency</span>
#Html.DropDownListFor(m => m.LightAgencies.agencykey, new SelectList(Model.LightAgencies.Agency, "Key", "Value"), "", new {#id = "OwnerAgency" })
<span class="LabelNormal">Agent</span>
#Html.DropDownListFor(m => m.LightOwnerAgent.au_key, new SelectList(""), "", new { #id = "OwnerAgent" })
And i have my jquery like,
$(document).ready(function () {
$("#OwnerAgency").change(function () {
var procemessage = "<option value=`0`> Please wait...</option>";
$("#OwnerAgent").html(procemessage).show();
var url = "/Index/GetOwnerAgent/";
// Get agency key
var OwnerAgency = $("#OwnerAgency :selected").val();
// Get agent
var OwnerAgent = $("#OwnerAgent :selected").val();
$.ajax({
url: url,
data: { agencykey: OwnerAgency },
cache: false,
type: "POST",
success: function (data) {
var OwnerAgent = $("#OwnerAgent :selected").val();
alert(OwnerAgent);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
where my controller "/Index/GetOwnerAgent/" giving the exact value for OwnerAgent. As iam the beginner i dont know how to do this, Kindly tell me.
In your code, you display the selected value in the dropdownlist as soon as the controller responds. I think you want to select the result from the controller in the dropdown.
Assuming that the data returned from the controller is a value that exists in the dropdownlist, you should be able to use:
...
success: function (data) {
$("#OwnerAgent").val(data);
}
...

Categories