I'm trying to setup a basic DropDownListFor in MVC:
#Html.DropDownListFor(modelItem => item.CheckerApproved, new SelectList(new SelectListItem { Text = "True", Value="1" } , new SelectListItem { Text = "False", Value="0"}))
This is in my view and what I'm wanting is a basic dropdown of true and false with values of 1 and 0 respectively.
I'm thinking the part I have wrong is adding the items to the SelectList constructor.
Can somebody help me with this?
Try this:
#Html.DropDownListFor(modelItem => modelItem.CheckerApproved, new [] { new SelectListItem { Text = "True", Value="1" } , new SelectListItem { Text = "False", Value="0"} })
For something like this, why don't you simply just emit a Select tag with Options in your view ?
<select id='ddlTrueFalse' name='ddlTrueFalse'>
<option value='1'>True</option>
<option value='0'>False</option>
</select>
Then in your Action add the parameter:
public ActionResult MyAction(string ddlTrueFalse)
{
//ddlTrueFalse will be "1" or "0"
}
I've had to do a few of these, and I actually wrote this as an extension method to HtmlHelper, but its a lot cleaner, its easy to debug and it's faster for the site in general.
This already exists -- if you do Html.EditorFor(model => model.MyBoolean) you will get a drop down list with True/False and a default of Unset or similar.
I had a hard time figuring out how to add a "class" to the code above, so I shared this, had to put original dropdown list in brackets, then add an overload
#Html.DropDownListFor(modelItem => modelItem.CheckerApproved, (new[] { new SelectListItem { Text = "True", Value = "1" }, new SelectListItem { Text = "False", Value = "0" } }), new { #class = "form-control" } )
#Html.DropDownListFor(modelItem => modelItem.CheckerApproved, (new[] { new SelectListItem { Text = "Selected", Value = "1" }, new SelectListItem { Text = "Not Selected", Value = "0" } }), new { #class = "form-control" } )
I add this as additional info, as it allows the designed to choose the name of the drop down option while allowing the programming team to still force a bool. Separation of form from design.
Related
I have bind the dropdownlist in view by Viewbag from controller as following :
ViewBag.test = from p in _userRegisterViewModel.GetEmpPrimary().ToList().Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
select new
{
Id = p.EmpId,
Name = p.First_Name.Trim() + " " + p.Last_Name.Trim()
};
In view I have bind as following :
#Html.DropDownListFor(model => model.EmpId, new SelectList(#ViewBag.test, "Id", "Name"),
new { #class = "form-control", id="ddlEmp" })
Now i want to Insert "ALL" and "--Select--" in this dropdownlist.. How can i do this..
Can anyone help me to do this..
Thanks in advance..
You can add a null option to the dropdownlist by using one of the overloads of DropDownlistFor() that accepts a optionLabel, for example
#Html.DropDownListFor(m => m.EmpId, new SelectList(#ViewBag.test, "Id", "Name"), "--select--", new { #class = "form-control", id="ddlEmp" })
which will generate the first option as <option value="">--select--</option>
However, if you want to include options with both "--select--" and "ALL" you will need to generate you own IEnumerable<SelectListItem> in the controller and pass it to the view. I would recommend using view model with a IEnumerable<SelectListItem> property for the options, but using ViewBag, the code in the controller would be
List<SelectListItem> options = _userRegisterViewModel.GetEmpPrimary()
.Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
.Select(a => new SelectListItem
{
Value = a.EmpId.ToString(),
Text = a.First_Name.Trim() + " " + a.Last_Name.Trim()
}).ToList();
// add the 'ALL' option
options.Add(new SelectListItem(){ Value = "-1", Text = "ALL" });
ViewBag.test = options;
Note that I have given the ALL option a value of -1 assuming that none of your EmpId values will be -1
Then in the view, your code to generate the dropdownlist will be
#Html.DropDownListFor(m => m.EmpId, (Ienumerable<SelectListItem>)ViewBag.test, "--select--", new { #class = "form-control" })
Not sure why your wanting to change the id attribute from id="EmpId" to id="ddlEmp"?
Then in the POST method, first check if ModelState is invalid (if the user selected the "--select--" option, a value of null will be posted and the model will be invalid), so return the view (don't forget to reassign the ViewBag.test property).
If ModelState is valid, then check the value of model.EmpId. If its -1, then the user selected "ALL", otherwise they selected a specific option.
I have on drop down.
Model
[Required(ErrorMessage = "Please selectvehicle")]
public string VehicleRequested { get; set; }
index.cshtml
#Html.DropDownList("VehicleRequested", new List<SelectListItem>
{
new SelectListItem{ Text="Active", Value = "1" },
new SelectListItem{ Text="Not-Active", Value = "0" }
})
#Html.ValidationMessageFor(model => model.VehicleRequested)
I cannot see the required feild validation append, M i wrong any where , please suggst
Your dropdownlist only has 2 items, one with value="0", the other with value="1" Both "0" and "1" are valid strings (neither are null) so validation always passes. Your property can never be invalid so you never get a validation error.
Its not really clear why your binding a int value to string property, and the fact you display only 2 values ("Active" and "Not-Active") suggests you property really should be a bool.
If you want to add an option such as "-please select-" that results in a validation error if one of the other 2 options is not selected, then use the overload that accepts optionLabel
#Html.DropDownList("VehicleRequested", new List<SelectListItem>
{
new SelectListItem{ Text="Active", Value = "1" },
new SelectListItem{ Text="Not-Active", Value = "0" }
}, "-Please select-")
#Html.ValidationMessageFor(model => model.VehicleRequested)
This will add the first option as <option value>-Please select-</option>. Note that the value attribute does not have a value, so if its selected when you submit, VehicleRequested will be null and you will see the error message.
Side note: Suggest you use the strongly typed helper - #Html.DropDownListFor(m => m.VehicleRequested, ...) and that you build the your Selectist in the controller and pass it to the view as a ViewBag or (better) a view model property.
Use #Html.DropDownListFor()
#Html.DropDownListFor((model => model.VehicleRequested, new List<SelectListItem>
{
new SelectListItem{ Text="Active", Value = "1" },
new SelectListItem{ Text="Not-Active", Value = "0" }
})
im using a example code to understand viewbag.
here is a bunch of code
in controller :
List<SelectListItem> dropdownItems = new List<SelectListItem>();
dropdownItems.AddRange(new[]{
new SelectListItem() { Text = "Option One", Value = "1" },
new SelectListItem() { Text = "Option Two", Value = "2" },
new SelectListItem() { Text = "Option Three", Value = "3" }});
ViewBag.dropdownItems = dropdownItems;
return View();
in View:
#Html.DropDownList("Types", ViewBag.dropdownItems as List<SelectListItem>)
#Html.ValidationMessageFor(model => model.Types)
the example was using ViewData, i use here viewbag to practice ..
#Html.DropDownList("Types", ViewBag.dropdownItems as List<SelectListItem>) is used for dropdown part.. but what is the use of #Html.ValidationMessageFor(model => model.Types) here..??
i remove #Html.ValidationMessageFor(model => model.Types) and the result is remain same.. My question is what is the actual impact of it and why should we use it ...??
It is not related at all.
When building your models in MVC, you add metadata notations to it like
[Required]
string Name {get; set;}
Now in the view,when you add
#Html.ValidationMessageFor(model => model.Name)
In this place a validation message would show if the name text-input wasn't filled.
I have an action that retrieves data and sends it to a view. In a view I have two dropdown menus.
First drop down shows salutation (such as "Mr.", "Ms.", etc.) and does not select value I sent for some reason. The other dropdown shows language list and correctly selects value I sent to the view. The relevant code in view is shown below.
#Html.DropDownListFor(model => model.Salutation, ViewBag.salutation as IEnumerable<SelectListItem>)
#Html.DropDownListFor(model => model.Language, ViewBag.languages as IEnumerable<SelectListItem>)
In the controller I have the following code to get the dropdown data.
ViewBag.salutation = new List<SelectListItem>() {
new SelectListItem() { Text = "", Value = "" },
new SelectListItem() { Text = "Mr.", Value = "Mr." },
new SelectListItem() { Text = "Ms.", Value = "Ms." },
new SelectListItem() { Text = "Mrs.", Value = "Mrs." }
};
and
var languages = (from l in db.Languages.ToList()
select new SelectListItem()
{
Text = l.Language,
Value = l.LanguageId.ToString()
}).ToList();
languages.Insert(0, new SelectListItem() { Text = "", Value = "" });
ViewBag.languages = languages;
The only difference I could think of is that the languages dropdown has an integer as value, whereas salutation dropdown has text as value. Is this why the salutation dropdown doesn't work? I know I could go through each salutation List<SelectListItem> item and set Selected property based on the value I retrieved from database. But I was hoping there would be a cleaner way to do this.
Any ideas?
Thanks
UPDATE
I decided to do what I did for another project.
IList<SelectListItem> _salutation = new List<SelectListItem>()
{
new SelectListItem() { Value = "", Text = "" },
new SelectListItem() { Value = "Mr.", Text = "Mr." },
new SelectListItem() { Value = "Ms.", Text = "Ms." },
new SelectListItem() { Value = "Mrs.", Text = "Mrs." }
};
// I could put the following in the declaration above, but for testing purposes it's in foreach loop.
foreach (var item in _salutation)
{
// compare to what's retrieved from database
item.Selected = item.Value == _viewData.Salutation;
}
ViewBag.salutation = _salutation;
After foreach loop I output .Value, .Selected property of each item in _salutation and I get all the correct values with one item being selected. Inside the view I did the following.
#foreach (var item in ViewBag.salutation as IEnumerable<SelectListItem>)
{
<b>#item.Value : #item.Text : #item.Selected</b><br />
}
All the correct Text/Values come up but none are Selected! This happens if I output the values after I execute #Html.DropDownListFor(). If I output the ViewBag.salutation before the html helper the correct value is selected.
SOLUTION
I found the following article useful: DropDownListFor with ASP.NET MVC.
Instead of using ViewBag I added the following to the ViewModel. (Showing the part for salutations drop down.)
public class TheViewModel
{
private IList<string> _salutations = new List<string>() { "", "Mr.", "Ms.", "Mrs." };
public IEnumerable<SelectListItem> SalutationItems
{
get
{
var salutations = _salutations.Select(s => new SelectListItem { Value = s, Text= s });
return salutations;
}
}
// The rest of the ViewModel
}
And in the View I have the following.
#Html.DropDownListFor(model => model.Salutation, Model.SalutationItems)
Instead of just supplying the list to the DropDownListFor helper you could provide it a SelectList. The SelectList constructor takes the list and allows you to explicitly set the selected value as well as an overload that lets you specify the Text and Value fields.
#Html.DropDownListFor(model => model.Salutation,
new SelectList(ViewBag.salutation as IEnumerable<SelectListItem>,
"Value", "Text", Model.Salutation))
Try this,
#Html.DropDownListFor(m =>m.DDCountryModel,IEnumerable<SelectListItem>)ViewBag.salutation)
#Html.DropDownListFor(model => model.Language, IEnumerable<SelectListItem>)ViewBag.languages)
Your Model should be like this,
public class Model
{
public IEnumerable<SelectListItem> DDCountryModel{ get; set; }
public IEnumerable<SelectListItem> Language{ get; set; }
}
I am making a MVC4 webapp for peers at 2 colleges to use, and later on I will expand to other schools. In my model I currently have
public string school { get; set; }
I would like it so when I do
#Html.EditorFor(model => model.school)
It would be a drop down of "school 1" and "School 2".
How can I go about doing this cleanly? If I can, I would like to be able to make the change in the model and not have to do anything in the view besides call #Html.EditorFor. If the only way to accomplish this is do something in the view, that is OK as well.
Instead of Html.EditorFor you can use Html.DropDownListFor
#{
var items = new SelectList(new[]
{
new SelectListItem {Text = "School1", Value = "School1"},
new SelectListItem {Text = "School2", Value = "School2"},
}, "Text", "Value");
}
#Html.DropDownListFor(x => x.school, #items)
Either you can use above code or you can go with this code in your page.
#Html.DropDownListFor(model => model.Status, new List<SelectListItem>
{
new SelectListItem{ Text="New", Value = "New" },
new SelectListItem{ Text="InProcess", Value = "InProcess" },
new SelectListItem{ Text="Completed", Value = "Completed" },
new SelectListItem{ Text="Rejected",Value="Rejected"},
}, "Select Status", new { #class = "form-control select2_demo_4" })
This will surely help you out and you can get value in your model when you select any of it.