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);
}
Related
I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is my controller.
public class DokuzasController : Controller
{
public ActionResult AddOrEdit()
{
DersViewModel model = new DersViewModel();
schoolEntities sc = new schoolEntities();
List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();
model.DersList = (from s in dersList
select new SelectListItem
{
Text = s.Ders1,
Value = s.DersID.ToString()
}).ToList();
model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel model)
{
if (model.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
TempData["SuccessMessage"] = "Saved.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
TempData["SuccessMessage"] = "Successful.";
}
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult SaatList(int id)
{
schoolEntities sc = new schoolEntities();
List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
List<SelectListItem> itemList = (from i in saatList
select
new SelectListItem
{
Value = i.SaatID.ToString(),
Text = i.Saat1
}).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
}
And this is my AddOrEdit file.
#model Mvc.Models.DersViewModel
#{
ViewBag.Title = "AddOrEdit";
}
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
#Html.DropDownListFor(m => m.SaatID, Model.SaatList)
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#DersID").change(function () {
var id = $(this).val();
var saatList = $("#SaatID");
saatList.empty();
$.ajax({
url: '/Dokuzas/SaatList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
saatList.append('<option value=' + option.Value + '>'
+ option.Text + '</option>')
});
}
});
});
});
</script>
}
I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?
in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownList("DersID", Model.DersList as SelectList)
<select name="id" id="SaatID" data-url="#Url.Action("SaatList","Home")">
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
<script type="text/javascript">
$(function(){
$("#DersID").change(function (e) {
var $SaatID = $("#SaatID");
var url = $SaatID.data("url")+'?id='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>
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);
}
I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/
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" ... }) %>