Validate static dropdown in MVC5 - asp.net-mvc

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" }
})

Related

DropdownlistFor not getting selected value?

I have a DropdownlistFor that is not getting the value that is chosen in the DDL. I've done some research and tried implementing some of the suggestions I've seen but mine still isn't working.
I'm using an IEnumerable<SelectListItem> as well as a string property to hold that selected value in my view model.
public IEnumerable<SelectListItem> AvailableSeats { get; set; }
public string Seat { get; set; }
I set the Seat property to an initial value when the ViewModel is created.
Seat = "FO";
This is how I'm populating my SelectListItem. "FO" is always an option but they have "CA" I add that to the SelectList as well.
public static List<SelectListItem> GetAvailableSeats(string currentSeat)
{
List<SelectListItem> seats = new List<SelectListItem>();
seats.Add(new SelectListItem { Text = "FO", Value = "FO" });
if (currentSeat.ToUpper() == "CA")
seats.Add(new SelectListItem { Text = "CA", Value = "CA", Selected = true });
return seats;
}
This is my Razor View:
#Html.DropDownListFor(m => m.Seat, Model.AvailableSeats, new { #class = "form-control" })
The HTML that gets produced is:
<select class="form-control" id="Seat" name="Seat">
<option value="FO">FO</option>
<option selected="selected" value="CA">CA</option>
</select>
However, when I select "FO" as my option and then submit my form, the ViewModel still has "CA".
I finally stumbled across the problem after going through this
post.
I'm posting in case it might help someone else. Inside my form I was assigning the the "Seat" property to a hidden field #Html.HiddenFor(m => m.Seat) and I didn't nee to do that. Getting rid of that hidden field fixed the problem.

Include 'ALL' option in dropdownlist bind using ViewBag

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.

Dropdownlistfor selected item not selecting using viewbag

I have dropdownlistfor which is getting populated from viewbag string array
<td>#Html.DropDownListFor(m => Model[i].start_operation, new SelectList(ViewBag.ValidOpers))</td>
<td>#Html.DropDownListFor(m => Model[i].end_operation, new SelectList(ViewBag.ValidOpers))</td>
It is not selecting the selected item based on Model[i].start_operation and end_operation
ViewBag.ValidOpers = new[] { "One", "Two", "Three", "Four"};
Unable to figure out why it is not selecting. I check giving just a Html.DisplayFor(m=>Model[i].start_operation to check if it is getting the values and yes it is getting the value and displaying correctly in the label, but the same value is not getting selected in the dropdownlistfor.
To over-answer your question:
Try first adding a not-mapped member to your model class:
e.g.
[NotMapped]
static public List<SelectListItem> myListOptions { get; set; }
then in the controller you can have
MyNameSpace.Models.MyModel.myListOptions = db.myTable.Select(uA=> new SelectListItem{ Value = uA.myColumn, Text = uA.myColumn}).Distinct().OrderBy(uA=>uA.Text).ToList();
// if you want string constants use:
MyNameSpace.Models.MyModel.myListOptions = new List<SelectListItem>();
MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "a", Value = "a"});
MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "b", Value = "b" });
then in the view, you use:
<div class="editor-field">
#Html.DropDownListFor(model => model.myField, MyNameSpace.Models.MyModel.myListOptions )
#Html.ValidationMessageFor(model => model.myField)
</div>

MVC3 model - how to make it so editorfor is a dropdown?

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.

MVC DropDownListFor basic True False in View

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.

Resources