MVC passing list from controller to viewBag - asp.net-mvc

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.

Related

Validate static dropdown in MVC5

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

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.

Set dropdown item selected MVC

I have multiple dropdown list for same select list in look and want to set dropdown item selected as per loop.
How can I set specific one item of dropdown list selected in mvc dropdownlist.
Please help.
The Html.DropDownList method takes multiple parameters, one of them being a List<SelectListItem>. The individual instance of the SelectListItem is where you set the Selected property:
var item = new SelectListItem() {
Selected = /* condition */,
Value = "Some Value",
Text = "Some Text"
};
Alternatively:
Create a SelectList collection that exposes the SelectedValue property:
Model.YourSelectList = new SelectList(items /* List<SelectListItem> */,
"Value",
"Text",
37 /* selected value */);
When building the SelectList, you can set the selected item on construction using http://msdn.microsoft.com/en-us/library/dd460123.aspx
Or you can set it on an individual SelectListItem via it's Selected property ( http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.selected.aspx ) and use the single-parameter constructor of the select list, or pass it straight to the DropDownList method.
Use the HTML helper ListBoxFor.
#Html.ListBoxFor(m => m.MyPropertyId, Model.MySelectList)
To build the list of items, you can use the MultiSelectList. For example, in your controller:
public ActionResult Index()
{
// Get a collection of all product id's that should be selected.
int[] productIds = _service.GetSomeProductIds();
// Make a new select list with multiple selected items.
ViewBag.List = new MultiSelectList(
_service.Products,
"Id", // Name of the value field
"Name", // Name of the display text field
productIds ); // list of selected product ids
return View();
}
Then in your view:
#Html.ListBoxFor(m => m.ProductIds, (IEnumerable<SelectListItem>)ViewBag.List)
MVC method to bind custom list to dropdownlist and select item dynamically
if you need more details ,comment below
Create Section
#{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
}
<div class="form-group">
#Html.LabelFor(model => model.SaleOrPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SaleOrPurchase, list, "-- Select Status --", new {#class= "form-control" })
#Html.ValidationMessageFor(model => model.SaleOrPurchase, "", new { #class = "text-danger" })
</div>
</div>
EDIT Section
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
IEnumerable<SelectListItem> myCollection = list.AsEnumerable();
ViewBag.SaleOrPurchase = new SelectList(myCollection, "Value", "Text", transactionTbl.SaleOrPurchase.ToString().Trim());

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