I have a working cascading dropdown list, whereby, once I select one value, it populates the second dropdown by use of JSON. I don't know how to pass this second dropdownlist index (and also whenever it is changed) to my controller to display corresponding data from my model.
My json dropdownlist is as follows
$(function () {
$('#VoyageDivID').hide();
$('#tabsDiv').hide();
$('#Vessel_ID').change(function () {
var URL = $('#VesselVoyageFormID').data('voyagelistaction')+'/' + $('#Vessel_ID').val();
$.getJSON(URL, function (data) {
var items = "";
$.each(data, function (i, voyage) {
items += "<option value='" + voyage.Value + "'>" + voyage.Text + "</option>";
});
$('#Voyage_ID').html(items);
$('#VoyageDivID').show();
$('#tabsDiv').show();
});
});
$('#Voyage_ID').change(function () {
$('#tabsDiv').show();
//need to show the related data here whenever the dropdownlist is changed
});
});
VIEW
<div id="tabsDiv">
<div class="editor-label">
XYZ
</div>
<div class="editor-field">
#Html.EditorFor(model => model.XYZ)
</div>
</div>
CONTROLLER
public ActionResult VoyageList(int ID)
{
// int voyageID = ID;
var voyages = from s in db.EXAMPLE.OrderByDescending(i => i.Voyage_ID).ToList()
where s.Vessel_ID == ID
select s;
if (HttpContext.Request.IsAjaxRequest())//only if it comes from list
return Json(new SelectList(
voyages.ToArray(),
"Voyage_ID",
"Voyage_ID")
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Index");
}
Related
I am using jQuery to set the second dropdown list items on selection of the first dropdown. At the time of edit action I want to set fetched data to the second dropdown list. I want to set ViewBag.UserLinkedList to the second dropdown list.
View:
<div class="form-row">
<div class="col-lg-7">
#Html.Label("User Type") #Html.DropDownListFor(m => m.LoginUserTypeID(SelectList)ViewBag.LoginUserTypeList, "--- Select User Type ---", new { #class = "form-control" })
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
#Html.Label("Parent User") #Html.DropDownListFor(m => m.UserLinkedID, new SelectList(""), "--- Select ---", new { #class = "form-control" })
</div>
<script>
$(document).ready(function() {
$("#LoginUserTypeID").change(function() {
$.get("/User/GetParentUserList", {
UserTypeID: $("#LoginUserTypeID").val()
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
})
});
</script>
Controller:
public JsonResult GetParentUserList(int UserTypeID)
{
List<V_Dealer_DealerEmployee> LinkedIDList = new List<V_Dealer_DealerEmployee>();
if (UserTypeID == 1 || UserTypeID == 2)
{
var d = from s in db.VDNSEmployeeMaster
select new
{
Id = s.EmpId,
Name = s.FirstName + " " + s.MiddleName + " " + s.LastName
};
d.ToList();
return Json(d.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
var unionAll = (from word in db.VDNSDealer select new
{
Id = word.m_code,
Name = word.institute_name
}).Concat(from word in db.DealerEngineerMaster select new {
Id = word.EnggId,
Name = word.EngineerName
});
return Json(unionAll.ToList(), JsonRequestBehavior.AllowGet);
}
}
Edit Action
public ActionResult Edit(int id)
{
var user = db.Users.SingleOrDefault(c => c.Id == id);
if (user == null)
return HttpNotFound();
List<LoginUserType> LoginUserTypeList = db.LoginUserType.ToList();
ViewBag.LoginUserTypeList = new SelectList(LoginUserTypeList, "UserTypeId", "UserTypeName");
List<V_Dealer_DealerEmployee> UserLinkedList = db.VDealerDealerEmployee.ToList();
ViewBag.UserLinkedList = new SelectList(UserLinkedList, "Id", "Name");
return View("New", user);
}
After returning view from edit action, you need to call your change function of LoginUserTypeID. Here is the required js for you
function UpdateUserLinkedIdDropdown(){
var userTypeId = $("#LoginUserTypeID").val();
//This check is for no options selected in LoginUserTypeID Dropdown
if(userTypeId === null || userTypeId === "" || userTypeId === undefined)
userTypeId = 0;
$.get("/User/GetParentUserList", {
UserTypeID: userTypeId
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
}
$("#LoginUserTypeID").change(function() {
UpdateUserLinkedIdDropdown();
});
// Call it initially when view loaded
// You can do it in this way
UpdateUserLinkedIdDropdown();
// OR This way
$("#LoginUserTypeID").trigger('change');
Give it a try! I think this will work. If not comment plz
Following is my cascasde dropdown list query. Countries list loading up but non of the states loading up in my dropdown list. if someone can help me to rectify the query please.
public ActionResult CountryList()
{
var countries = db.Countries.OrderBy(x=>x.CountryName).ToList();
// IQueryable countries = Country.GetCountries();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(
countries,
"CountryID",
"CountryName"), JsonRequestBehavior.AllowGet
);
}
return View(countries);
}
public ActionResult StateList(int CountryID)
{
IQueryable <State> states= db.States. Where(x => x.CountryID == CountryID);
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
states,
"StateID",
"StateName"), JsonRequestBehavior.AllowGet
);
return View(states);
}
following is the View file also containg java script:
#section scripts {
<script type="text/javascript">
$(function () {
$.getJSON("/Dropdown/Countries/List",function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, country) {
items += "<option value='" + country.Value + "'>" + country.Text + "</option>";
});
$("#Countries").html(items);
});
$("#Countries").change(function () {
$.getJSON("/Dropdown/States/List/" + $("#Countries > option:selected").attr("value"), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$("#States").html(items);
});
});
});
</script>
}
<h1>#ViewBag.Title</h1>
#using (Html.BeginForm())
{
<label for="Countries">Countries</label>
<select id="Countries" name="Countries"></select>
<br /><br />
<label for="States">States</label>
<select id="States" name="States"></select>
<br /><br />
<input type="submit" value="Submit" />
}
First of all, your action method name is StateList which expects a parameter named CountryID. But your code is not making a call to your StateList action method with such a querystring param. So fix that.
$("#Countries").change(function () {
$.getJSON("#Url.Action("StateList","Home")?CountryID=" +
$("#Countries").val(), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$("#States").html(items);
});
});
I also used #Url.Action helper method to get the correct url to the action method with the assumption that your StateList action method belongs to HomeController. Update the parameter according to your real controller name as needed.
Now, In your action method, you should not try to return the IQueryable collection, you may simply project the data to a list of SelectListItem and return that.
public ActionResult StateList(int CountryID)
{
var states = db.States.Where(x => x.CountrId==CountryID).ToList();
//this ToList() call copies the data to a new list variable.
var stateOptions = states.Select(f => new SelectListItem {
Value = f.StateID.ToString(),
Text = f.StateName }
).ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(stateOptions, JsonRequestBehavior.AllowGet);
return View(states);
}
Is it possible to get the selectedIndex of a dropdown in a view using C# (Razor). For example, can I fill a second dropdown based off the selectedIndex of another dropdown using Razor?
#model ViewModel
<select id="dropdown1">
//Options
</select>
<select id="dropdown2">
//Options
</select>
#if(//The selectedIndex of dropdown1 == 4)
{
//Fill dropdown 2 from model
}
When using Javascript, I am a little off as well:
<script>
if (dropdown1.selectedIndex === 3)
{
#foreach (var item in Model)
{
}
}
</script>
You can do it using a ajax call when the first dropdown changes:
<script type="text/javascript">
function getDropDown2Data(id) {
$.ajax({
url: '#Url.Action("GetDropDown2Data", "YourController")',
data: { Id: id },
dataType: "json",
type: "POST",
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Name + "\">" + item.Id + "</option>";
});
$("#dropDown2").html(items);
}
});
}
$(document).ready(function () {
$("#dropDown2").change(function () {
var id = $("#dropDown2").val();
getDropDown2Data(id);
});
});
</script>
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model1, "Id", "Name"), "Select")
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model2, "Id", "Name"), "Select")
And you action:
[HttpPost]
public ActionResult GetDropDown2Data(id id)
{
//Here you get your data, ie Model2
return Json(Model2, JsonRequestBehavior.AllowGet);
}
I have to do one dropdownlist and one listbox. When I select a value in dropdownlist, the listbox has to change. I'm trying to do this with Jquery, because I'm using MVC. But when I select the ID in the first dropdownlist, nothing happens. My code:
View (Jquery):
<script type="text/javascript">
$(document).ready(function () {
$('#IDCONCESSAO').change(function () {
$.ajax({
url: '/Localidades/LocalidadesMunicipio',
type: 'POST',
data: { ConcessaoId: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
$.each(data, function () {
options += '<option value="' + this.IdLocalidade + '">' + this.NomeLocalidades + '</option>';
});
$('#IDLOCALIDADE').prop('disabled', false).html(options);
}
});
});
});
</script>
Dropdownlist and listbox part:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, new SelectList(ViewBag.IDCONCESSAO, "Id", "Nome"), new { #class = "select", style = "width: 250px;" }) %>
</div>
<div class="editor-label" style="font-weight: bold">
Localidades:
</div>
<div class="editor-field" id="Localidades">
<%: Html.ListBoxFor(m => m.SelectedItemIds, Model.ItemChoices, new { id = "IDLOCALIDADE", size = "10" })%>
</div>
The action that do the cascade:
[HttpPost]
public ActionResult LocalidadesMunicipio(int ConcessaoID)
{
var Localidades = (from s in db.LOCALIDADES_VIEW
join c in db.SINCO_CONCESSAO.ToList() on s.ID_MUNICIPIO equals c.IDMUNICIPIO
where c.IDCONCESSAO == ConcessaoID
select new
{
idLocalidade = s.ID_LOCALIDADE,
NomeLocalidades = s.NOME_LOCALIDADE
}).ToArray();
return Json(Localidades);
}
Controller:
[Authorize(Roles = "ADMINISTRADOR")]
public ActionResult Create(SINCO_LOCALIDADE_CONCESSAO model)
{
//Here I populate my dropdownlist
ViewBag.IDCONCESSAO = from p in db.SINCO_CONCESSAO.ToList()
join c in db.MUNICIPIOS_VIEW.ToList() on p.IDMUNICIPIO equals c.ID_MUNICIPIO
join d in db.SINCO_TIPO_CONCESSAO.ToList() on p.IDTIPOCONCESSAO equals d.IDTIPOCONCESSAO
select new
{
Id = p.IDCONCESSAO,
Nome = p.IDCONCESSAO + " - " + c.NOME_MUNICIPIO + " - " + d.DSTIPOCONCESSAO
};
//Here I populate my listbox
PopulateItemLocalidades(model);
return View(model);
}
I can't see what is wrong T_T
What I am missing?
The first drop down most likely has an ID of SINCO_CONCESSAO, by the name of the property it was created for. And you are referring to something different in your script.
To fix this, either specify a different ID in jQuery:
$('#SINCO_CONCESSAO').ajax ...
or set an ID for a dropdown in View:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, ...
, new { id = "IDCONCESSAO" ... }) %>
The Following is the View :
<div class="editor-label">
Select Currency :
</div>
<div class="editor-field">
#Html.DropDownList("CurrencyId", new SelectList(ViewBag.CurrencyId, "Value", "Text"))
</div><div class="editor-label">
Select GameType :
</div>
<div class="editor-field">
#Html.DropDownList("GameTypeId", new SelectList(ViewBag.GameTypeId, "Value", "Text"), new { style = "width:100px" })
#Html.ValidationMessageFor(model => model.GameTypeId)
</div>
<div class="editor-label">
Select Category :
</div>
<div class="editor-field">
#Html.DropDownList("CategoryByGameType", Enumerable.Empty<SelectListItem>(), "Select Category")
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
The following is Controller:-
public ActionResult Create()
{
List<Currency> objCurrency = new List<Currency>();
objCurrency = db.Currencies.ToList();
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "0",
Text = "Select Currency"
});
foreach (Currency item_Currency in objCurrency)
{
listItems.Add(new SelectListItem()
{
Value = item_Currency.CurrencyId.ToString(),
Text = item_Currency.CurrencyName
});
}
ViewBag.CurrencyId = new SelectList(listItems, "Value", "Text");
List<GameType> objgametype = objGameByGameType.GetDistinctGameTypeID();
List<SelectListItem> listItems_1 = new List<SelectListItem>();
listItems_1.Add(new SelectListItem()
{
Value = "0",
Text = "Select Game Type"
});
foreach (GameType item_GameType in objgametype)
{
listItems_1.Add(new SelectListItem()
{
Value = item_GameType.GameTypeId.ToString(),
Text = item_GameType.GameTypeName
});
}
ViewBag.GameTypeId = new SelectList(listItems_1, "Value", "Text");
return View();
}
The following is my Jquery for i am using Casceding Dropdown
$(function () {
$("#GameTypeId").change(function () {
var theatres = "";
var gametype = "";
var mytestvar = "";
var gametypeid = $(this).val();
mytestvar += "<option value= -1 >Select Category</option>";
$.getJSON("#Url.Action("GetCategoryByGameType", "GameCombination")?gametypeid=" + gametypeid, function (data) {
$.each(data, function (index, gametype) {
// alert("<option value='" + gametype.Value + "'>" + gametype.Text + "</option>");
mytestvar += "<option value='" + gametype.Value + "'>" + gametype.Text + "</option>";
});
//alert(mytestvar);
$("#CategoryByGameType").html(mytestvar);
$("#GamebyCategory").html("<option value=0>Select Game</option>");
$("#LimitVariantByGameByGameType").html("<option value=0>Select Limit Variant</option>");
$("#StakeCategory").html("<option value=0>Select Stake Category</option>");
$("#StakeBuyInByStakeCategory").html("<option value=0>Select Stake Buy In By Stake Category</option>");
});
});
});
While submit data i am not able to get back the dropdown value if Error come on creation
Echo of what Andras said, you can't use razor syntax in a .js file if that's happening.
Also you should get familiar with your debugging tools, what browser are you using? Most have a nice set of developer tools (some have them built in) where you can inspect the page and the request sent out when you submit the form.
You could interactively use jquery in the console of your browser to look around also.
You don't show your post create method, perhaps it is related to that code?
This should give you an idea of what you can do.
I would suggest that you move the ajax into its own function and the $.each into its own function and call the $.each function out of the ajax function and the ajax function out of the main function.
$(function () {
$("#GameTypeId").change(function () {
var theatres = "";
var gametype = "";
var mytestvar = "";
var gametypeid = $(this).val();
mytestvar += "<option value= -1 >Select Category</option>";
$.ajax({
url: '/GameCombination/GetCategoryByGameType',
type: 'GET',
data: { "gametypeid": gametypeid},
dataType: 'json',
success: function (data) {
$.each(data, function (index, gametype) {
// alert("<option value='" + gametype.Value + "'>" + gametype.Text + "</option>");
mytestvar += "<option value='" + gametype.Value + "'>" + gametype.Text + "</option>";
});
//alert(mytestvar);
$("#CategoryByGameType").html(mytestvar);
$("#GamebyCategory").html("<option value=0>Select Game</option>");
$("#LimitVariantByGameByGameType").html("<option value=0>Select Limit Variant</option>");
$("#StakeCategory").html("<option value=0>Select Stake Category</option>");
$("#StakeBuyInByStakeCategory").html("<option value=0>Select Stake Buy In By Stake Category</option>");
},
error: function (error) {
alert(error.toString());
}
});
});
});
You have to create a object for dropdownlist in View.cs and then assign the value. After that when u try to get the dropdown values u have to use the ViewBag title object name and then the dropdownlist value.
Below code specifies for the radiobutton. You can alter it for dropdown
#model MVC_Compiler.Models.UserProgram
#{
ViewBag.Title = "UserProgram";
}
<table style="background-color: #FBF9EF;">
<colgroup>
<col style="width: 20%;">
<col style="width: 80%;">
</colgroup>
<tr>
<td style="vertical-align: text-top">
#Html.RadioButtonFor(up => up.Language, "C")C<br />
#Html.RadioButtonFor(up => up.Language, "C++")C++<br />
#Html.RadioButtonFor(up => up.Language, "C#")C#<br />
#Html.RadioButtonFor(up => up.Language, "VB")VB<br />
#Html.RadioButtonFor(up => up.Language, "Java")Java<br />
#Html.RadioButtonFor(up => up.Language, "Perl")Perl<br />
#Html.HiddenFor(up => up.Language, new { #id = "Select_Language" })
#Html.HiddenFor(up => up.UserName, new { #id = "UserName" })
</td>
Then in Models you can get the radio button value by following way:
userProgram.Language
where userProgram is ViewBag Title.