I'm new to MVC, but I've been all over this, read all the documentation and all the questions and all the blog posts I can find, and all I'm doing is getting completely wrapped around the axle.
I'm trying to make a "create" Action and View. My data entry is relatively straight forward, and common: I have a drop down list and a text box. In my case, I'm creating a user contact channel, and the drop down box chooses between email and textmsg, and the text box then enters the relevant contact information, either a well formed email address, or a mobile phone number.
Here's a (slightly simplified form of) my View page:
<tr>
<td><%= Html.DropDownList("ChannelDescription", Model.ChannelDescription, "Select a Channel", new { id = "ChannelDDL", onchange="ChannelDDLChanged()" })%>
<br />
<%= Html.ValidationMessage("ChannelDescription", "Please Select a Channel") %>
</td>
<td>
<%= Html.TextBox("SubscriberNotificationAddr") %> <br />
<%= Html.ValidationMessage("SubscriberNotificationAddr", "Please enter a contact address or number") %>
</td>
</tr>
I'm using a strongly typed ViewData model, rather than using the ViewDataDictionary. The ChannelDescription element is a SelectList, which is initialized with the list of choices and no selection.
The initial display of the form, the data entry into the form, and the extraction of the data from the form by the controller goes fine.
My problem is if the data contains an error, such as a mal-formed email address or cell phone number, and I have to return to the view, I have not been successful in getting the drop down list selection redisplayed. The ChannelDescription element is recreated in the controller with the user's choice as the selected item. I have set breakpoints on that line of the View, and verified that the selected element of the list of items has the Selected property set to true, but it still displays the default "Select a Channel".
This seems like it would be a very common situation, and shouldn't be this hard. What am I doing wrong?
FYI, this is with MVC 1.0 (Release), Windows 7, and VS 2008, running under Firefox 3.5.2.
After viewing the answer above, I wanted to check it out, because all the examples I had seen had, indeed, used ViewDataDictionary, rather than a strongly typed ViewDataModel.
So I did some experiments. I constructed a very simple view that used a plain ViewDataDictionary, and passed values in by named keys. It persisted the selected item just fine. Then I cut and pasted that View (and controller) to another one, changing only what was necessary to switch to a strongly typed ViewData Model. Lo, and behold, it also persisted the selected item.
So what else was different between my simple test and my application? In my test, I had used simply "Html.DropDownList("name", "optionLabel")". However, in my application, I had needed to add HTML attributes, and the only overloads available that included HtmlAttributes also include the select List.
It turns out that the DropDownList overload with a select list parameter is broke! Looking at the downloaded MVC source code, when DropDownList is called with just a name, or a name and an optionLabel, it ends up retrieving the target select list from the ViewData, and then invoking the private SelectInternal method by the following call:
return SelectInternal(htmlHelper, optionLabel, name, selectList, true /* usedViewData */, false /* allowMultiple */, (IDictionary<string, object>)null /* htmlAttributes */);
However, if it's called with a selectList parameter, it ends up with the following:
return SelectInternal(htmlHelper, optionLabel, name, selectList, false /* usedViewData */, false /* allowMultiple */, htmlAttributes);
The difference is that in the first one (which will work correctly) the "usedViewData" parameter is true, while in the second one, it is false. Which is actually okay, but exposes an internal defect in the SelectInternal routine.
If usedViewData is false, it gets a object variable "defaultValue" from the ViewData model.
However, defaultValue is used as though it is either a string or an array of strings, when, in fact what is returned from the ViewData is a SelectList. (IEnumerable<SelectListItem>).
If usedViewData is true, then defaultValue will be either null or a string.
Then if defaultValue is not null, it ends up going into a block of code which contains this:
foreach (SelectListItem item in selectList) {
item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
newSelectList.Add(item);
selectList is the original selectList that was passed in, so the item is a SelectListItem (string Text, string Value, and bool Selected). But selectedValues was derived from the defaultValue, and becomes a List of SelectLists, not a List of strings. So for each of the items, it's setting the Selected flag based on whether the selectedValues list "Contains" the item.Value. Well, a List of SelectLists is never going to "Contain" a string, so the item.Selected never gets set. (Correction: actually, after more tracing with the debugger, I found that selectedValues is derived from the defaultValue by a "ToString()" call. So it actually is a list of strings, but instead of containing the values that we want, it contains "System.Web.Mvc.SelectList" - the result of applying "ToString()" to complex object like a SelectList. The result is still the same - we're not going to find the value we're looking for in that list.)
It then substitutes the newly constructed "newSelectList" for the original "selectList", and proceeds to build the HTML from it.
As cagdas (I apologize for butchering your name, but I don't know how to make those characters on my US Keyboard) said above, I think I'll have to build my own method to use in place of the DropDownList HtmlHelper. I guess since this release 1 and Release2 is in Beta 2, we can't really expect any bug fixes unless we do it ourselves right?
BTW, if you've followed me this far, this code is in src\SystemWebMvc\Mvc\Html\SelectExtensions.cs, at around line 116-136
I had some discussions with Brad Wilson, from the MVC team, and he explained to me that I was misunderstanding how the DropDownList helper method should be used (a misunderstanding that I think might be fairly common, from what I've read).
Basically, EITHER give it the SelectList in the named parameter of the ViewModel, and let it build the drop down list from that with the appropriate items selected, OR give it the SelectList as a separate parameter and let the named parameter of the ViewModel be just the value strings for the selected item(s). If you give it a SelectList parameter, then it expects the named value to be a string or list of strings, NOT a SelectList.
So, now your ViewModel ends up having two elements for one conceptual item in the view (the dropdown list). Thus, you might have a model that has
string SelectedValue {get; set;}
SelectList DropDownElements { get; set;}
Then you can pre-populate the DropDownElements with the choices, but in your model view binding, you just need to deal with SelectedValue element. It seems to work pretty well for me when I do it that way.
Yes, I too had so many problems getting DropDownList to respect the selected item I've given to it.
Please check my answer in this question. As far as I can remember, that was the only way I could get it to work. By passing the list via ViewData.
FYI, I stopped using that HtmlHelper method. I'm now simply outputting the <select> and <option> tags myself with a loop and setting the selected property of the option tag by checking it myself.
Related
I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList:
ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");
Then I am rendering my DropDownListFor as follow inside my View:
#Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")
As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?
You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).
When using #Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).
When using #Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation
Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.
There is not harm to use it. You will not get any error. but best practice is to bind model property.
I have never asked a question on StackOverflow before, and never wanted to, but I am desperate, so here we go: I cannot get a saved value to show up as the default value/display in a dropdown.
I set up the list in my controller:
public ActionResult Index()
{
//User Dropdown List
var users = Roles.GetUsersInRole("Manager");
SelectList list = new SelectList(users);
ViewBag.Users = list;
return View();
}
Then in the view an admin can then select one of these users and save it to my database via EF:
#Html.DropDownList("Users", ViewBag.Users as SelectList, "--Select Manager--")
This all works great, however, when you edit this entry, I want the dropdown list to show the current saved manager, not the first name in the list. I was hoping on my edit action that I could pull the current manager out of the database and pass it back into the dropdown as the default selected item, but no go:
public ActionResult Edit(int id = 0)
{
var theOwner = (from v in _db.Location where v.LocationID == id select v.Owner).FirstOrDefault();
var users = Roles.GetUsersInRole("Manager");
SelectList list = new SelectList(users, theOwner);
ViewBag.Users = list;
From all the examples I have read over the last 2 weeks, everyone has had 3 different values to work within their dropdowns, making it possible to use all the overloads in the SelectList method. However, my problem is that I just have this string list with only one item in it, so I can't utilize the overloads as I want.
So does anyone have an idea on how I can get this to work? Thanks a lot in advance for your time on this!
I'm pretty sure that if you modify the second parameter on the line where you create your SelectList, it should work -- it does for me.
Here is what I think the trouble is: Currently you are specifying the second parameter as 'theOwner', which is an object reference from the earlier Linq statement. But the SelectList contains a bunch of strings (the UserNames of the users which match the specified rolename). As a result, the SelectList doesn't 'know' how to match what you specified as the SelectedItem to something in the list of strings it contains.
But if you refine that second parameter so it specifies the USERNAME of the Owner that you just looked up, it should work. However I do not know what the correct property name is from your Location table. If the field you are currently selecting (v.Owner) contains the UserName itself rather than some Key then the syntax would be:
SelectList list = new SelectList(users, theOwner.Owner);
If that column actually contains a key for the User like an int or a Guid then you will have query for the UserName using the key, but the nature of the fix is the same.
Hope that helps.
A quick workaround is not to use #Html.DropDownList but plain html code.
As an example for your case, use the following html code in your View instead of Html.DropDownList helper:
<!-- NOTE: the ID and name attributes of "select" tag should be the same as
the name of the corresponding property in your Model in order for ASP.NET MVC
to edit your Model correctly! -->
<select id="User" name="User">
#foreach (var user in (SelectList)ViewBag.Users)
{
if (user == ViewBag.TheOwner)
{
<option value="#user" text="#user" selected = "selected" />
}
else
{
<option value="#user" text="#user" />
}
}
</select>
Also , for this to work you need to add one more line to your Edit method:
ViewBag.TheOwner = theOwner;
Another solution is also possible using #Html.DropDownListFor() however you haven't shown your model so I can't tell you what exactly to use. When DropDownListFor is used, ASP.NET MVC will select an option automatically based on the value in your model.
I have a class called "PropertyFeature" which simply contains PropertyFeatureID and Description. It's a proper model created through LINQ to SQL mapped to an SQL Server database table. An example instance/row would be:
PropertyFeatureID: 2
Description: "Swimming Pool"
The number of rows (PropertyFeatures) can of course grow and shrink, and so I want to dynamically render a list of checkboxes so that the user can select any of them.
I can dynamically render the Checkboxes easily enough, with something like:
<%foreach (var Feature in (ViewData["Features"] as IEnumerable<MySolution.Models.PropertyFeature>)) { %>
<%=Html.CheckBox("Features", new { #id = Feature.PropertyFeatureID, #value = Feature.PropertyFeatureID })%><label for="Feature<%=Feature.PropertyFeatureID%>"><%=Feature.Description%></label>
<%}%>
I specify the ID for each checkbox and render the matching label so that the user can intuitively click the label and toggle the checkbox - that works great.
I set the CheckBox's "name" to "Features" so all the checkboxes render with the same name, and the MVC Model Binder piles them into a single collection called "Features" when the form is posted. This works nicely.
Once the form is submitted, I use the checked values and store them, so I need the actual integer values so I know which PropertyFeature is selected, not just a pile of Booleans and field names. So ideally, I want it as an array or a collection that's easy to work with.
I am able to retrieve the selected values from within my Controller method when the button is clicked because I have specified the parameter as int[] Features.
But the problem is that it doesn't maintain state. That is, when I click the submit button and the page reloads (with the form again displayed) I want all of the dynamic checkboxes to retain their checked status (or not). All of the other fields that I've created with Html.DropDownList and Html.TextBox all maintain their states successfully no problems at all on the same page in the same form.
I have spent hours reading all of the other threads and articles on similar issues and there is a lot of talk about using ICollection and IDictionary to bundle things up and include a Boolean value for each item so that it can maintain the checkbox state. But I don't 100% grasp how to use that in the context of my own personal example. I would like to keep the solution really simple and not have to code up pages of new classes just to maintain my checkbox state.
What is the cleanest and proper way to do this?
I got it working after much playing around with the various different approaches.
In the view:
<%string[] PostFeatures = Request.Form.GetValues("Features");%>
<% foreach (var Feature in (ViewData["AllPropertyFeatures"] as
IEnumerable<MySolution.Models.PropertyFeature>))
{ %>
<input type="checkbox" name="Features"
id="Feature<%=Feature.PropertyFeatureID.ToString()%>"
value="<%=Feature.PropertyFeatureID%>"
<%if(PostFeatures!=null)
{
if(PostFeatures.Contains(Feature.PropertyFeatureID.ToString()))
{
Response.Write("checked=\"checked\"");
}
}
%> />
<label for="Feature<%=Feature.PropertyFeatureID%>">
<%=Feature.Description%></label> <%
} %>
In the receiving controller method:
public ActionResult SearchResults(int[] Features)
This method has a number of advantages:
Allows labels to be clicked to toggle the corresponding checkboxes (usability).
Allows the Controller method to receive a super tidy array of ints, which ONLY contains the ints that have been selected - and not a whole other pile of items which were unselected or containing false/null/blank/0 etc.
Retains the checkbox's checked state when the page reloads containing the form, i.e. the user's selection is retained.
No random/stray type=hidden input fields created from the default ASP.Net MVC Html.CheckBox helper - I know it does those for a good reason, but in this instance, I don't require them as I only want to know about which IDs have been selected and for those to be in a single, tidy int[].
No masses of additional server side bloated classes, helpers and other happy mess required to achieve such a simple thing.
I would recommend this approach for anyone wanting the cleanest / bloat-free solution for a dynamic checkbox list where you need the IDs and you just want to get down to business!
The problem is that when you are rendering your list of checkboxes, you aren't setting any of them as selected. You will need to set your int[] Features in ViewData, and then in your foreach loop, check to see if the ID of that Feature is in the array in ViewData.
something like:
<%=Html.CheckBox("Features",
((int[])ViewData["SelectedFeatures"]).Contains(Feature.PropertyFeatureID),
new { #id = Feature.PropertyFeatureID, #value = Feature.PropertyFeatureID })%
although I didn't test it, so it might not be 100%.
I have a usercontrol that is rendering a list of items. Each row contains a unique id in a hidden field, a text and a delete button. When clicking on the delete button I use jquery ajax to call the controller method DeleteCA (seen below). DeleteCA returns a new list of items that replaces the old list.
[HttpPost]
public PartialViewResult DeleteCA(CAsViewModel CAs, Guid CAIdToDelete)
{
int indexToRemove = CAs.CAList.IndexOf(CAs.CAList.Single(m => m.Id == CAIdToDelete));
CAs.CAList.RemoveAt(indexToRemove);
return PartialView("EditorTemplates/CAs", CAs);
}
I have checked that DeleteCA is really removing the correct item. The modified list of CAs passed to PartialView no longer contains the deleted item.
Something weird happens when the partial view is rendered. The number of items in the list is reduced but it is always the last element that is removed from the list. The rendered items does not correspond to the items in the list/model sent to PartialView.
In the usercontrol file (ascx) I'm using both Model.CAList and lambda expression m => m.CAList.
How is it possible for the usercontrol to render stuff that is not in the model sent to PartialView?
Thanx
Andreas
It sounds like the ModelState is the trouble here, as you bind to CAs the ModelState save this values in the background as Attempted Values, so its true the object is no longer present at the Model, but the ModelSate still have the values of the deleted object. You can try a:
ModelState.Clear();
To remove all those old values.
Check in firebug what the response realy is. This way you can see if you have a serverside problem or it is a jquery issue.
Hey all, this is a newbie ASP.NET MVC question.
I have a view that has a list of checkboxes and a submit button. On submit it posts to a controller method but I can't figure out how to get the values of the checkboxes. Also, I can't figure out how to get model data that I passed into the view when I'm in the post method, I tried using Html.Hidden but that didn't seem to work.
Here's the code:
http://pastebin.com/m2efe8a94 (View)
http://pastebin.com/m39ebc6b9 (Controller)
Thanks for any input received,
Justin
First thing I noticed is that your hidden fields need to be inside your form. Currently in your view, they are above the BeginForm, so they won't be included in the form submission.
To get the values of the selected check boxes, add an IsOffered parameter to your OfferTrade Action method.
public ActionResult OfferTrade(FormCollection result, List<string> IsOffered)
That parameter will contain a list of the ItemId's for all the checked IsOffered boxes.
The HtmlHelper's CheckBox works differently and I don't like the way it works, so I don't use it.
Making the IsOffered parameter type List<int> should also work if your ItemId field is an integer.
First of all your ItemId and UserId is outside your form:
<%= Html.Hidden("ItemId", Model.ItemIWant.ItemId) %>
<%= Html.Hidden("UserId", Model.ItemIWant.UserId) %>
//...
<% using (Html.BeginForm()) {%>
Secondly you could try to make your Controller action method use "model binding" (if this is also called model binding)
public ActionResult OfferTrade(int ItemId, int UserId, IList<string> IsOfferred)
Edit Just noticed you are not using the HtmlHelper CheckBox so your list will contain only selected items, but a point still:
You might want to look into Phil Haacks post on Model Binding To A List, but there is a small change to this in the RTM version of MVC:
You dont need the ".Index" hidden fields, but then the indexes in the Name fields must be zero-indexed and increasing (by 1).