ASP.Net MVC SelectList not 'Selecting' Correct Item - html

I have been asked to look at a bug in some ASP.Net MVC code and have a (to me) very odd problem with a SelectList.
The code from the controller to generate the items (a method to return a SelectList, there are 5 in total). Each SelectList is then saved into the ViewData collection.
List<SelectListItem> items = new List<SelectListItem>();
string yesText = "Yes";
string noText = "No";
if (ci.LCID.Equals((int)LanguageCodes.FRANCE))
{
yesText = "Oui";
noText = "Non";
}
SelectListItem yesItem = new SelectListItem();
yesItem.Text = yesText;
yesItem.Value = ((int)MarketingBy.Yes).ToString();
yesItem.Selected = selectedValue != null && selectedValue.Equals(int.Parse(yesItem.Value));
SelectListItem noItem = new SelectListItem();
noItem.Text = noText;
noItem.Value = ((int)MarketingBy.No).ToString();
noItem.Selected = selectedValue != null && selectedValue.Equals(int.Parse(noItem.Value));
items.Add(yesItem);
items.Add(noItem);
return new SelectList(items, "Value", "Text", yesItem.Selected ? yesItem.Value : noItem.Value);
A quick 'quickwatch' at the point of creation suggests everything is ok:
At the point the view is being rendered, the values still look ok. However when the view loads, the first item in the list is always selected. The HTML generated is:
<tr>
<td>Fax</td>
<td>
<select id="MarketingByFax" name="MarketingByFax">
<option value="134300002">Yes</option>
<option value="134300001">No</option>
</select>
</td>
</tr>
(Other values ommitted for clarity).
Any ideas? Or avenues to research? The author is adamant that this was working 'up til last week' (I have no idea either way).
Edit: Code for the view -
<td><%: Html.DropDownList("MarketingByFax", (SelectList)ViewData["MarketingByFaxList"])%></td>

This code looks just horrible in every imaginable aspect (IMHO of course). I have no idea why it doesn't work and I don't want to know. All I can do is to suggest you how to improve it (so you can stop reading this post if you are looking for a solution about why your code doesn't work as I have no freaking idea).
So the first improvement would be to get rid of any ViewData and introduce a view model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
then I would have a controller action that would populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
// I want to preselect the second value
SelectedValue = "No",
Items = new[]
{
new SelectListItem { Value = "Yes", Text = "yeap !" },
new SelectListItem { Value = "No", Text = "nope !" },
}
};
return View(model);
}
and in my strongly typed view I would simply bind the helper to the view model:
<%= Html.DropDownListFor(
x => x.SelectedValue,
new SelectList(Model.Items, "Value", "Text")
) %>
Also if you want to work with some enum types you may find the following extension method useful.
See how easy it is? No more ugly casts with ViewData, no more need to define any lists and specify some complicated conditions, ...
Remark: once again, those are just my 2ยข, you can continue the combat with ViewData if you will.

you can try
<%: Html.DropDownList("MarketingByFax", (IEnumerable<SelectListItem>)ViewData["MarketingByFaxList"])%>
dropdwon has an overload that accepts the enumeration of Selectlist type objects and it sets the value of list automatically depending upon Selected property of selectListItems in the list. for this you have to set
ViewData["MarketingByFaxList"] = items;//where item is IEnumerable<SelectListItem> or List<SelectListItem> as you used in your code

Related

DropDownFor change event not firing

I have the following Razor markup:
#Html.DropDownListFor(x => Model.WorkTypeId, new SelectList(Model.WorkTypeList, "Id", "Name", Model.WorkTypeId), " - please select - ", new { style = "background-color: yellow;"})
#Html.DropDownListFor(x => Model.PhaseGroupId, new SelectList(Model.PhaseGroupList, "Id", "Name", Model.PhaseGroupId), " - please select - ", new { style = "background-color: yellow;"})
Then I load the form these reside on using a jQuery $.get call, and assign change handlers to both dropdowns in the success function of the call:
function(data) {
$("#formContainer").html(data);
$("#WorkTypeId").change(function () {
lookupMatrixValues($("#WorkTypeId").val(), $("#PhaseGroupId").val());
});
$("#PhaseGroupId").change(function () {
lookupMatrixValues($("#WorkTypeId").val(), $("#PhaseGroupId").val());
});
})
When I select an item in the WorkTypeId dropdown, the change event does not fire, while if I select a PhaseGroupId item, its event does fire.
Also, when I POST the form, no matter what value is selected for a worktype, the value of the model property WorkTypeId is always zero, as if the select itself doesn't detect a change event.
If I look at what is rendered for the DropDownFor markup, I see the two selects are rendered slightly differently:
<select id="WorkTypeId" name="WorkTypeId" style="background-color: yellow;">
...
<select data-val="true" data-val-number="The field PhaseGroupId must be a number." id="PhaseGroupId" name="PhaseGroupId" style="background-color: yellow;">
I am curious as to why only the PhaseGroupId select has the data-val and data-val-number attributes while the WorkTypeId select does not have these attributes. The model properties are exactly the same:
public int? WorkTypeId { get; set; }
public int? PhaseGroupId { get; set; }
Why is the WorkTypeId select rendered differently and why does its bound model property never reflect what is selected. No matter what is selected, $("#WorkTypeId").val() is always zero.
You have a strange lambda syntax. IMHO should be
#Html.DropDownListFor(m=> m.WorkTypeId, ... //or model=>model.WorkTypeId
#Html.DropDownListFor(m => m.PhaseGroupId ...
and check if you have another WorkTypeId somewhere in your view. Javascript binds the first id it meets.

DropDownListFor not populating selected value

Probably a frequently asked question, but I didn't found any answer matching my problem.
I got a SelectList like, which I want to show in a DropDown:
var selectList = new SelectList(listItems, "Text", "Value", selectedCustomer);
#Html.DropDownListFor(model => model.Name, selectList, "-- Select Customer --")
The list holds the correct values, one is selected. But the dropdownlist shows only the text "-- Select Customer --".
Populating listItems:
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (Customer c in Model.GetAllCustomer())
{
listItems.Add(new SelectListItem { Text = c.Id, Value = c.Name });
}
To clarify my question: The dropdown works fine on most sites (it's in the layout page). But sometimes after a POST request it does not show any selected value. All the provided code is in the layout page.

how to bind dropdownlist in view dynamically ? mvc4

I want to replace this code in my view
Code :
<label for="name">Lead Source</label><select name="Lead_Source" id="Lead_Source" rel="2">
<option value="1">News Papers </option>
<option value="2">Internet</option>
<option value="3">Social networking</option>
<option value="4">Others</option>
</select>
I want to replace with Dropdownlist so I will bind data dynamically by I am getting undone by work .
I tried like this:
<label for="name">Lead Source</label> #Html.DropDownListFor(c=>c.Lead_Source, Model.Lead_Source_List,"--Select Source--");
The error i am getting after i replace static code is
CS1928: 'System.Web.Mvc.HtmlHelper<Ibs.Iportal.Iwise.Web.Models.LeadSortModel>' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, object)' has some invalid arguments
EDIT : I am passing a model to view which contain a Lead_Source_List of enumerable list data
Regards
you should create a view model and make strongly typed view,do something like this in you action:
public ActionResult YourAction(int id)
{
var model = new MyViewModel();
using (var db = new SomeDataContext())
{
// Get the boxer you would like to edit from the database
model.Boxer = db.Boxers.Single(x => x.BoxerId == id);
// Here you are selecting all the available weight categroies
// from the database and projecting them to the IEnumerable<SelectListItem>
model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
{
Value = x.WeightCategoryId.ToString(),
Text = x.Name
})
}
return View(model);
}
this chunk is populating select list item:
model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
{
Value = x.WeightCategoryId.ToString(),
Text = x.Name
})
and assigned to model
Now use in view this way:
#model MyViewModel
#Html.DropDownListFor(
x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
Model.WeightCategories
)

How to get the value of selectlist in view into controller with or without Json

I can get the value of a dropdownlist this way but i cant get the value of a selectlist item with this code. What i can do to get the value into my controller for my create action.
My Controller Contains :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product products, Design designs, Material materials, Color colors, Picture pictures, FormCollection form,EventArgs e)
{
if (Request.Files != null)
{
long prod = Convert.ToInt64(form["Product"]);
pictures.product_id = db.Products.Single(x => x.id == prod).id;
My View Contains :
#Html.DropDownList("Product", new SelectList((System.Collections.IEnumerable)ViewData["Productlist"], "id", "name"), "Please Select Product", new { onchange = "productlist()", style = "width:190px; padding:4px; margin:4px;" })
i can get dropdownlist value but cant get the value of selectlist..
My View Contains : (SelectList)
<select id="Color" style=" width:190px; padding:4px; margin:4px;" onchange="colorlist()">
<option label="Please Select Color" ></option>
</select>
so if im gonna need to use json how can i use it inside create action and in view.
If you want to use the default binding, then you need an argument in your Create action named "Product" of whatever type you are passing (i.e. string). Then when the form POSTs to the action the binder will set that argument value to the option selected at the time of POST.

How do I get the collection of Model State Errors in ASP.NET MVC?

How do I get the collection of errors in a view?
I don't want to use the Html Helper Validation Summary or Validation Message. Instead I want to check for errors and if any display them in specific format. Also on the input controls I want to check for a specific property error and add a class to the input.
P.S. I'm using the Spark View Engine but the idea should be the same.
So I figured I could do something like...
<if condition="${ModelState.Errors.Count > 0}">
DisplayErrorSummary()
</if>
....and also...
<input type="text" value="${Model.Name}"
class="?{ModelState.Errors["Name"] != string.empty} error" />
....
Or something like that.
UPDATE
My final solution looked like this:
<input type="text" value="${ViewData.Model.Name}"
class="text error?{!ViewData.ModelState.IsValid &&
ViewData.ModelState["Name"].Errors.Count() > 0}"
id="Name" name="Name" />
This only adds the error css class if this property has an error.
<% ViewData.ModelState.IsValid %>
or
<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>
and for a specific property...
<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection
To just get the errors from the ModelState, use this Linq:
var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
Condensed version of #ChrisMcKenzie's answer:
var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
This will give you one string with all the errors with comma separating
string validationErrors = string.Join(",",
ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToArray());
Putting together several answers from above, this is what I ended up using:
var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToList();
validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.
Thanks Chad! To show all the errors associated with the key, here's what I came up with. For some reason the base Html.ValidationMessage helper only shows the first error associated with the key.
<%= Html.ShowAllErrors(mykey) %>
HtmlHelper:
public static String ShowAllErrors(this HtmlHelper helper, String key) {
StringBuilder sb = new StringBuilder();
if (helper.ViewData.ModelState[key] != null) {
foreach (var e in helper.ViewData.ModelState[key].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Here is the VB.
Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())
If you don't know what property caused the error, you can, using reflection, loop over all properties:
public static String ShowAllErrors<T>(this HtmlHelper helper) {
StringBuilder sb = new StringBuilder();
Type myType = typeof(T);
PropertyInfo[] propInfo = myType.GetProperties();
foreach (PropertyInfo prop in propInfo) {
foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Where T is the type of your "ViewModel".
Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:
var errors =
from item in ModelState
where item.Value.Errors.Count > 0
select item.Key;
var keys = errors.ToArray();
Source: https://forums.asp.net/t/1805163.aspx?Get+the+Key+value+of+the+Model+error