I am trying to get my head around drop down lists with MVC, which appears to be failing me. I've been tinkering with the code shown below but can't get it right.
What I am trying to achieve is simple - hard coding some drop down options in the controller, have them appear in the Razor rendered html and when an option is selected, that selected value is bound back to the string property in the model.
With the code below I can't access li from within the View.
I've seen other guides but I haven't been able to make it work, is binding model the best option for me, given what I'm trying to achieve, or would ViewBag etc be better?
Could someone show me where I'm going wrong please?
Model
public class ViewModel {
public string MyOption { get; set; } }
View
#model ViewModel
#Html.DropDownListFor(m => m.MyOption, li, "--Select--")
Controller
public ActionResult Index()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Option One", Value = "option1" });
li.Add(new SelectListItem { Text = "Option Two", Value = "option2" });
return View(li);
}
You need to pass MyOption to view if you want to use it. A valid option would be to creaete a view model class containing all information you need to handle on your view
ViewModel
public class ViewModel
{
public IList<SelectListItem> ItemList {get; set;}
public string MyOption { get; set; }
}
View
#Html.DropDownListFor(m => m.MyOption, Model.ItemList, "--Select--")
Controller
public ActionResult Index()
{
var li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Option One", Value = "option1" });
li.Add(new SelectListItem { Text = "Option Two", Value = "option2" });
var viewModel = new ViewModel
{
ItemList = li,
MyOption = [here your code to fill this]
}
return View(viewModel);
}
you need to make sure you are declaring your model in the view in order to access any attributes or modifiers to that model
#model Namespacehere.Models.modelclassname
then you should be able to use something like
#Html.DropDownListFor(m => m.MyOption, model, "--Select--")
Related
Here is the Syntax of My Dropdown.
#Html.DropDownListFor(model => model.DealerIdRef, Model.Ddllist, " Select Dealer ", new { #class = "form-control"})
i want its default selected value and make it read-only so that user can not update selection. For this i'm using Jquery.
$('#DealerIdRef').val('#Session["MyID"]').trigger('change');
$("#DealerIdRef").attr('disabled', 'true');
this is setting the value and also exists in Console
At Controller it is still null
Edit
if i'm making some mistake then please help.
thanks in advance
Your javascript is setting the disabled attribute of the dropdownlist. Disabled form controls do not submit a value so the value of DealerIdRef in your model is its default (i.e. null because its int?).
If you want the value of the dropdownlist to be submitted, do not disabled it.
But based on i want its default selected value and make it read-only so that user can not update selection, then there is no point generating a dropdownlist, and in anycase, you set selected option by setting the value of the property your binding to. That is you set the value of DealerIdRef in the GET method before you pass the model to the view.
Since all you want is to display a value and have it posted back, then include a hidden input for the value and display the text
#Html.HiddenFor(m => m.DealerIdRef)
<div>...the txt you want to display...</div>
There is no point degrading performance by generating a SelectList and extra html when its not needed.
As a side note, your POST method would have throw this exception because you have not repopulated the SelectList in the POST method before you return the view.
I wrote a simple mock your question.
It can work. The simple code is on DropDownController
Here is the Source Code,I Upload to github.
ViewModel
public class DropDownViewModel
{
[Display(Name = "Dealer")]
public int? DealerIdRef { get; set; }
public IEnumerable<SelectListItem> Ddllist { get; set; }
}
Index View
Mock Your Submit action
#model Sample.Models.DropDownViewModel
#using (Html.BeginForm("ShowDDL", "DropDown", FormMethod.Post))
{
#Html.DropDownListFor(model => model.DealerIdRef, Model.Ddllist, " Select Dealer ", new { #class = "form-control" })
<button>Submit</button>
}
ShowDDL View
Show your select data.
#model Sample.Models.DropDownViewModel
<b>Your Select Value: </b> #Model.DealerIdRef
DropDownController
public ActionResult Index()
{
DropDownViewModel model = new DropDownViewModel()
{
Ddllist = GetDDL(),
DealerIdRef = 1
};
return View(model);
}
[HttpPost]
public ActionResult ShowDDL(DropDownViewModel viewModel)
{
return View(viewModel);
}
private IEnumerable<SelectListItem> GetDDL()
{
return new List<SelectListItem>()
{
new SelectListItem()
{
Text = "One",
Value = "1"
},
new SelectListItem()
{
Text = "Two",
Value = "2"
}
};
}
I've been working for a while on this, I know how to resolve it using JQuery, but I need to solve this just using server side code, I'm in a Razor View
The thing is:
I have an #Html.DropDownlist that is showing some States from USA, and once clicked one of the States from the DropDownList then I want to show some cities that belong to the State selected using other DropDownList, I'm not sure how to get the value from the selected field just using Razor syntax and then show the cities that belong to the State in other DropDownList when one State is selected, I'm using a SelectList and I have an StateID to bind the cities... I'm showing all the States inside a DropDownList that is working.
Here is my code:
These are just two classes that I'm using to fill the SelectList with some properties:
public States(int id, string name, List<string> list)
{
StateID = id;
Name = name;
Cities = list;
}
public int StateID { get; set; }
public string Name { get; set; }
public List<string> Cities { get; set; }
}
public static class Fill
{
public static List<States> GiveMeStates()
{
List<States> li = new List<States>() {
new States(1, "Alabama",new List<string> {"Adamsville", "Addison", "Anderson","Anniston", "Arab" }),
new States(2,"Alaska", new List<string> {"Anchorage","Juneau","Fairbanks","Sitka"}),
new States(3,"Arizona", new List<string> { "Avondale", "Benson", "Besbee"})
};
return li;
}
}
And now this is my Razor View:
#using RazorMVC.Models;
#{
List<States> aux = Fill.GiveMeStates();
SelectList states = new SelectList(aux, "StateID", "Name");
}
<form>
#Html.DropDownList("ddlStates", states);
</form>
If you absolutely do not want to use javascript/jQuery, you may submit the form (with the selected state id) and get the states based on the posted state id and show that.
Assuming you want to show the cities for the selected state in the same view.
#{
var stateId = Request.QueryString["ddlStates"] as string;
List<States> aux = Fill.GiveMeStates();
SelectList states = new SelectList(aux, "StateID", "Name");
List<SelectListItem> cities = new List<SelectListItem>();
if (!String.IsNullOrEmpty(stateId))
{
var state = aux.FirstOrDefault(f => f.StateID == Convert.ToInt32(stateId));
if (state != null)
{
cities = state.Cities
.Select(x => new SelectListItem {Value = x, Text = x}).ToList();
}
}
}
<label>Select a state and hit submit </label>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
#Html.DropDownList("ddlStates", states)
<label>Cities < /label>
#Html.DropDownList("City", cities)
<input type="submit" />
}
I personally prefer to not put a lot of C# code in the razor views. I usually create a view model and use that to pass the values needed in the view. So most of the above code you see in the view goes in my action method.
If you prefer to use jQuery/javascript (Why not ?), You may listen to the change event of the the first dropdown ,get the selected option value and send that to server via an ajax call. Let your server action method returns the states in json format and your ajax metod's call back can parse the json data and update the cities dropdown. Here is a sample to start with
I am using ASP.NET MVC5 in my application.
I want to show languages known by an employee using check boxes in my view(check boxes with same name). For this how to write my model, pass them from the controller and display them in the view?
I have those vales stored in an Enum
public enum Language {
English=1,
Telugu=2,
Hindi=3,
Spanish=4
}
It is ok if I have to store them in a table in DB.
You can use the CheckBoxListFor helper:
#Html.CheckBoxListFor(model => model.SelectedOptions, Model.AllOptions)
And your model would look like this:
public class MyModel {
// This property contains the available options
public SelectList AllOptions { get; set; }
// This property contains the selected options
public IEnumerable<string> SelectedOptions { get; set; }
public MyModel() {
AllOptions = new SelectList(
new[] { "Option1", "Option2", "Option3" });
SelectedOptions = new[] { "Option1" };
}
}
In controller you just simply pass your model to the View:
[HttpGet]
[ActionName("Index")]
public ActionResult Index()
{
var model = new MyModel();
return View(model);
}
You can change the AllOptions and SelectedOptions properties as you want (just remove the code from the constructor of MyModel and place it in your controller class).
For more details check this out, there is a note about how to work with Enum: CheckBoxList for Enum types MVC Razor.
I'm newbie with ASP.Net MVC 5 and I'm having a problem understanding the dropdownlist.
I want show a form that binds a DTO object (because that form doesn't map one to one a database table). My form must show the following fields:
Name (edit box)
Address (edit box)
Type (dropdownlist that show always 3 fixed values: "Type1", "Type2" and "Type3"
How can I write my DTO object class and the two Create actions (the one that show the form and the other that handle the post)?
I found some solutions that use the enum in the DTO objects, others that use the viewbag in the create action (GET)...I'm confused!!!
Trick is to use SelectListItem and use DropDownFor.
Create a property on your view model like
public class ViewModel {
string SelectedItem { get; set; }
List<SelectListItem> Items { get; set; }
}
In your controller:
public ActionResult Edit() {
var items = new List<SelectListItem>() {
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"}};
var model = new ViewModel() { Items = items };
return View(model);
};
In your view
#model ViewModel
#Html.DropDownFor(x => x.SelectedItem, Model.Items)
You can then get the selected value in your action:
[HttpPost]
public ActionResult Edit(ViewModel model) {
var whatWasSelected = model.SelectedItem; // This will be "OptionXValue"
// Do more things
}
You should also re-populate the select list items on whatever action responds to the form submission if you're going to re-render the view. This is because the collection of options are not transmitted over the original request and therefore ASP.NET MVC doesn't know how to rebuild the collection by itself. By doing this you'll avoid any nasty exceptions when trying to set the selected item in the collection of SelectListItem. Overall the responding action would look more like:
[HttpPost]
public ActionResult Edit(ViewModel model) {
var items = new List<SelectListItem>() {
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"}};
model.Items = items;
var whatWasSelected = model.SelectedItem; // This will be "OptionXValue"
// Do more things
}
I want to add a dropdownlist in my form, with 2 values userid and username in my dropdownlist, and also I want to get the value selected by the user when I click the button. I'm new to MVC and so far, I have not worked on dropdownlist, tried few samples but nothing seems to be working the way I want.
I'll jump lots of MVC3 concepts. If you're really new to ASP.NET MVC, you should take a look at some tutorials.
This code should help you:
VIEW
#using (Html.BeginForm("ACTION NAME", "CONTROLLER NAME"))
{
<select name="select">
<option value="username" selected>User name</option>
<option value="userid">User id</option>
</select>
<input type="submit" />
}
ACTION
[HttpPost]
public ActionResult ACTIONNAME(string select)
{
//...
}
Please, note:
ACTION NAME and CONTROLLER NAME at the BeginForm helper. You will have to modify this at your code
The select name ("select") and the name of the argument at the action ("select"). This is not a coincidence, it's a convention. MVC uses the name attr to bind data
The selected attribute at the option will make it the default option
Regards
See one of the ways you can do it is send the list in a model property as the binding and for the value you can bind it to another property like :
public class YourModel
{
public List<UserList> OptionList { get; set; }
public String YourValue{get;set;}
}
public class UserList
{
public String UserName{get;set;}
public String UserId{get;set;}
}
#Html.DropDownListFor(model => model.YourValue, Model.OptionList, "")
In the helper there are overided options which are used to specify the value and text.
And Remember :
This is StackOverflow.
Even the Not working example which you have tried are important for the ones who try to help you since they are spending their precious bandwidths for u.
You don't need create a new model class for each view, just put this on controller:
ViewBag.FieldName = new SelectList(new List<SelectListItem>() {
new SelectListItem { Value = "userid", Text = "User ID" },
new SelectListItem { Value = "username", Text = "User name" }
});
And this on view:
#Html.DropDownList("FieldName")
You need to create a collection of SelectListItem like:
IEnumerable<SelectListItem> selectList =
from c in areaListResponse.Item
select new SelectListItem
{
Text = c.AreaName,
Value = c.Id.ToString()
};
Pass this selectList to your view:
return View(selectList);
In your cshtml:
#model IEnumerable<SelectListItem>
#Html.DropDownListFor(m => m.RequestAreaName, Model)
If you need complecated object, you may need a wrapper class like:
public class RaiseRequestModelWrapper
{
public IEnumerable<SelectListItem> GetModel { get; set; }
public RaiseRequestModel PostModel { get; set; }
}