Work on asp.net mvc5.My project DropDownList work perfectly problem arise when i disabled DropDownList control then can not get value in controller.
My razor syntax is bellow:
<div class="form-group">
#Html.LabelFor(m => m.ProductName, new {#class = "col-md-3 control-label"})
<div class="col-md-3">
#Html.DropDownList("ProductID", null, "Select product", new {#placeholder = "Select product", #class = "form-control", #disabled = "disabled" })
</div>
</div>
my controller syntax to fill the above DropDownList
private void LoadProductsInViewData(object selectedValue = null)
{
var datas = productRepository.GetAll().OrderBy(p => p.Name);
ViewBag.ProductID = new SelectList(datas, "ProductID", "Name", selectedValue);
}
Why In controller create/edit event can not get the DropDownList value?
Note:I know it's disabled control default behavior,i try to use hidden column like this.Problem is how hidden column used with my approach.
You can use Jquery to retrive the value of Currently Selected item of DropList which is disabled in your case, using
var dropDownValue=("#Id_of_u_Dropdownlist").val()
and you can send the DropDownValue variable which contains value of Disable Dropdown list to Controller.
This is a normal behavior. Disabled fields cannot be posted, then it's a common pratice to add a Html.HiddenFor() to post the disabled value.
As you said, there is no "ProductId" property in your model. However, if you create a Html.Hidden("ProductId", "YourValue") and add a parameter named 'productId' in your Controller Create/Edit action, the value should be subimitted.
Create an Httpost Action and then use FormCollection Object like this
[HttpPost]
public ActionResult GetDropDownValue(FormCollection Form)
{
string dropdownValue=form["ID_of_dropdownlist"].toString();
}
Related
I am new to Razor, I pass dropdown list as a viewbag and another values, when drop down list show in web it has selected values but i haven't set the any selected value, I think I use same name in viewbag value and dropdownlist value,it can be happen?
This is the viewbag,here i set the values and drop downlist:
ViewBag.GlobalInstance = globalInstance;
ViewBag.LegislativeCode = legislativeCode.Trim();
ViewBag.Legislatives = new SelectList(legislativeEntities, "LegislativeCode", "LegislativeName");
This is frontend code:
#if (ViewBag.GlobalInstance == true)
{
<div class="col-xs-5 hcm-form_controller mandatory gap" >
<label for="LegislativeCode" class="w-100" mi-resourcekey="atr-LegislativeCode" >Legislative Entity</label>
#Html.DropDownListFor(m => m.LegislativeCode, ViewBag.Legislatives as SelectList, "--- Select ---", new { #class = "calc-w-100" })
</div>
}
It seems that the page model has a value for LegislativeCode,
m => m.LegislativeCode
so when there is a same LegislativeCode in the ViewBag.Legislatives, this option will be selected.
I have a drop down list in c# MVC Razor application that is populated via enum data model object. My issue comes into play when the user selects the drop down the default value is the first value from the model and when it is selected the onchange event is not being triggered. Please see code below:
.net core mvc razor view
<tr>
<td>
<a id="GenderLnk" href="#">Click Here to Update</a><br>
<div id="GenderDiv" style="display:none;">
#using (Html.BeginForm("UpdateGender", "Home", FormMethod.Post))
{
#Html.DropDownListFor(m => m.StudentGender, new SelectList(Enum.GetValues(typeof(Gender))), new { #class = "show", onchange = "this.form.submit();" })
}
</div>
</td>
</tr>
Here is the model property
public Gender StudentGender { get; set; }
public enum Gender
{
Female,
Male,
[Display(Name ="Not Applicable")]
NotApplicable,
Transgender
}
The reason for not triggering the "onChange" function is, it technically does not change any value in the form if user selected the default value in the first attempt. What you can do is provide a value like "please select" as the default value and let the user choose a value in the list.
#Html.DropDownListFor(m => m.StudentGender, new SelectList(Enum.GetValues(typeof(Gender))), "-- Please Select -- ", new { #class = "show", onchange = "this.form.submit();" })
May be you can use this question + answer into consideration as well. Hope this helps.
Get a default NULL value from DropDownList in ASP.NET MVC
I'm trying to create an Item edit screen where the user can set a property of the Item, the ItemType. Ideally, when the user returns to the screen, the dropdown would display the ItemType already associated with the Item.
As it is, regardless of what the item.ItemType is, the dropdown will not reflect that in the dropdown. Is there a way around this?
For reference, my code at the moment is:
<div class="form-group">
#Html.LabelFor(model => model.ItemType, new { #class = "control-label col-xs-4" })
<div class="col-xs-8">
#Html.DropDownListFor(model => model.ItemType, (SelectList)ViewBag.ItemType, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemType, String.Empty, new { #class = "text-danger" })
</div>
</div>
The ViewBag is set with the following:
var ItemType = Enum.GetValues(typeof(ItemType));
ViewBag.ItemType = new SelectList(ItemType);
If you're using ASP.NET MVC 5, try just using the EnumHelper.GetSelectList method. Then you don't need ViewBag.ItemType.
#Html.DropDownListFor(model => model.ItemType, EnumHelper.GetSelectList(typeof(ItemType)), new { #class = "form-control" })
If not, you might need to specify the data value and data text fields of the select list.
var itemTypes = (from ItemType i in Enum.GetValues(typeof(ItemType))
select new SelectListItem { Text = i.ToString(), Value = i.ToString() }).ToList();
ViewBag.ItemType = itemTypes;
Then since it's an IEnumerable<SelectListItem> you'll need to change your cast.
#Html.DropDownListFor(model => model.ItemType, (IEnumerable<SelectListItem>)ViewBag.ItemType, new { #class = "form-control" })
Eventually I found a fix - manual creation of the list.
<select class="form-control valid" data-val="true"
data-val-required="The Item Type field is required." id="ItemType" name="ItemType"
aria-required="true" aria-invalid="false" aria-describedby="ItemType-error">
#foreach(var item in (IEnumerable<SelectListItem>)ViewBag.ItemType)
{
<option value="#item.Value" #(item.Selected ? "selected" : "")>#item.Text</option>
}
</select>
Try to keep as much of the logic outside of the View and in the Controller.
I saw in your self answer that it looks like you have an enum selected from wihin your controller.
I have a DropDownList in one of my apps that contains a list of Enums. It also has a default value selected, but also has specific enums available to the user. The default selection can be set from within the controller.
This example is based on what my needs were, so you'll need to adapt to your case.
In the controller:
public ActionResult Index()
{
ViewBag.NominationStatuses = GetStatusSelectListForProcessView(status)
}
private SelectList GetStatusSelectListForProcessView(string status)
{
var statuses = new List<NominationStatus>(); //NominationStatus is Enum
statuses.Add(NominationStatus.NotQualified);
statuses.Add(NominationStatus.Sanitized);
statuses.Add(NominationStatus.Eligible);
statuses.Add(NominationStatus.Awarded);
var statusesSelectList = statuses
.Select(s => new SelectListItem
{
Value = s.ToString(),
Text = s.ToString()
});
return new SelectList(statusesSelectList, "Value", "Text", status);
}
In the view:
#Html.DropDownList("Status", (SelectList)ViewBag.NominationStatuses)
This approach will automatically set the default item to the enum that was selected in the controller.
I'm new to MVC and JavaScript and I have a question about DropDownList.
I Build a program of "Car Renting" and I have a View that allow adding new Car to the inventory.
The view include 2 dropdownlists (see below):
<div class="editor-field">
#Html.DropDownList("ManufacturerId", string.Empty)
#Html.ValidationMessageFor(model => model.ManufacturerId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ModelId)
</div>
<div class="editor-field">
#Html.DropDownList("ModelId", string.Empty)
#Html.ValidationMessageFor(model => model.ModelId)
</div>
I want that when user select a manufacturer for example (Alfa Romeo) the "model" list box will display only "Alfa Mito" models and not the full list...
My Controller function send to the view the Model List using ViewBag see below:
public ActionResult AddNewCar()
{
ViewBag.ManufacturerId = new SelectList(db.Manufacturers, "ManufacturerId", "ManufacturerName");
ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName");
ViewBag.BranchId = new SelectList(db.Branchs, "BranchId", "BranchName");
return View();
}
Please advice.
Thanks,
Almog
call below action method from jquery on dropdown change event.
public List<carmodels> PopulateState(int manufacturerId)
{
var carmodelsObj = (from st in dc.Carmodels
where st.manufacturerId.Equals(manufacturerId)
select st).ToList();
return (carmodelsObj);
}
You need to repopulate/populate your ModelId dropdown on every time when your first dropdown changes (using jquery). Do following:
Get the ManufactureId from first dropdown on change event. and place an ajax call to repopulate your second dropdown.
$("#ManufactureId").change(function() {
var manufacturerId = manufacturer$('#ManufacturerId').val();
$.ajax({url: "~/Car/GetCarsByManufacturer", success: function(result){
//re populate your second dropdown here
//hint: you may use response.id for value
}});
});
Create a function in your controller that returns Car Models, based on selected. (call this function in previous step using ajax).
public List<carmodels> GetCarsByManufacturer(int manufacturerId)
{
var carmodelsObj = (from st in dc.Carmodels
where st.manufacturerId.Equals(manufacturerId)
select st).ToList();
return (carmodelsObj);
}
I trying to get a listbox for a module I've created to work. The selector works (the titles of the selectable entities appear but there is no data returned to the Post function in the controller.
I don't know what you would need to be able to help me, but here is at least the html code.
HTML code:
<div class="field required">
#Html.LabelFor(model => model.Sessions)
#Html.ListBox("Sessions", new SelectList(Model.Sessions, "Id", "Title", 1));
#Html.ValidationMessageFor(model => model.Sessions)
</div>
Use ViewBag in Controller
ViewBag.Sessions = new SelectList(EntityName, "Id", "Name", entity.ID);
entity.ID will be value which you want to select
#Html.DropDownList("Sessions", "Select Sessions")