Once again I'm confronted with a "This shouldn't be this ?*!# hard" situation.
Problem: I want to use a form in MVC for creation of an object. One of the elements of the object is a set of limited choices - a perfect candidate for a drop down list.
But if I use a SelectList in my model, and a drop down list in my View, and then try to post the Model back to my Create method, I get the error "Missing Method Exception:No Parameterless constructor for this object". Exploring the MVC source code, it appears that in order to bind to a model, the Binder has to be able to create it first, and it can't create a SelectList because there is no default constructor for it.
Here's the simplified code:
For the model:
public class DemoCreateViewModel
{
public SelectList Choice { get; set; }
}
For the controller:
//
// GET: /Demo/Create
public ActionResult Create()
{
DemoCreateViewModel data = new DemoCreateViewModel();
data.Choice = new SelectList(new string[] { "Choice1", "Choice2", "Choice3" });
ViewData.Model = data;
return View();
}
//
// POST: /Demo/Create
[HttpPost]
public ActionResult Create(DemoCreateViewModel form)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
And for the View:
<fieldset>
<legend>Fields</legend>
<%= Html.LabelFor(model => model.Choice) %>
<%= Html.DropDownListFor(model => model.Choice, Model.Choice) %>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
Now, I know I can MAKE this work by dropping back 10 yards and punting: bypass model binding and drop back to the FormCollection and validate and bind all the fields myself, but there's got to be a simpler way. I mean, this is about as simple a requirement as it gets. Is there a way to make this work within the MVC ModelBinding architecture? If so, what is it? And if not, how come?
Edit: Well, I have egg on my face, but maybe this will help someone else. I did some more experimenting and found a simple solution that seems to work.
Provide a simple value (string or integer, depending on what your select list value type is), and name that as the model element that you bind to. Then provide a second element as the select list of choices, and name it something else. So my model became:
public class DemoCreateViewModel
{
public string Choice { get; set; }
public SelectList Choices { get; set; }
}
And then the DropDownListFor statement in the View becomes:
<%= Html.DropDownListFor(model => model.Choice, Model.Choices) %>
When I do this, the submit button correctly binds the choice made in the form to the string Choice, and submits the model back to the second Create method.
Here is one approach:
#Html.DropDownListFor(model => model.Choice,
ViewBag.Choices as SelectList,
"-- Select an option--",
new { #class = "editor-textbox" })
Notice that I use ViewBag to contain my SelectList. This way when you post back, the client doesn't send the entire select list up to the server as part of the model.
In your controller code, you just need to set the view bag:
ViewBag.Choices = new SelectList(....
Consider creating a different view model for your post action without the SelectList property:
public class DemoCreateViewModelForUpdate
{
public string Choice { get; set; }
}
Then you can always map from the DemoCreateViewModelPost instance to an DemoCreateViewModel instance if the model state is invalid and you want to re-show the view. I tend to prefer everything needed by the view to be in my display view model class, so using a separate update only view model let's me keep things slim and trim for the trip back to the server.
In your view, you'd do:
#Html.DropDownListFor(m => m.Choice, Model.Choices)
as in the previous answer, so no unnecessary data would round trip.
Related
I'm new to MVC so this may sound silly, but here goes: I have a model that contains two lists that need to be passed to an edit form:
public class BaseViewModel
{
public IEnumerable<portal_notifications_types> Types { get; set; }
public IEnumerable<portal_notifications_importances> Importances { get; set; }
}
In the edit form, i Have two dropdownlists for this fields:
#Html.DropDownListFor(m => m.Notification.TypeId, new SelectList(Model.Types, "Id", "Type"), "-- Select type --", new { onchange = "GetNotifType();", style = "width:150px;" })
#Html.DropDownListFor(m => m.Notification.ImportanceId, new SelectList(Model.Importances, "Id", "Importance"), "-- Select importance --", new { style = "width:150px;" })
When I first enter the edit view, everything is ok, the dropdownlists are populated and the corresponding value is selected.
However, when I submit the form, the dropdownlists throw an error, because the Model.Types and Model.Importances lists are null.
How could I overcome this ? I would like to avoid using ViewBag to store those lists, although I know it would work.
Pass the View Model again in your Post Action Method.
[HttpPost]
public ActionResult Index(ViewModel m)
{
return View(m); //Pass the View Model again.
}
You have to repopulate these two SelectLists in the Controller POST method for Edit and again pass the ViewModel in the view for edit. Please share your Controller code for Edit for more details.
I'm trying to create an editor template that will create a "bootstrap style" radio buttons for each value from a passed select list (just like the Html.DropDownFor method create a dropdown list)
So i have the call in my view:
#Html.EditorFor(model => model.FaultTypeID,"RadioButtonList",
new SelectList(Model.AllowdeFaultTypes, "FaultTypeID", "FaultTypeName"))
and now the template of RadioButtonList:
#foreach (var item in ViewData["Items"] as SelectList)
{
<a>#item.Text</a> <b>#item.Value</b>
}
but the conversion fails and i get a NullReferanceExeption.
By reflection i see that the ViewData["Items"] value is of type System.Collections.Generic.List<CamelotFaultManagement.DAL.FaultType>
The problem is i really don't want to tightly couple the RadioButtonList editor template with CamelotFaultManagement.DAL.FaultType class, its just don't make any sense to do that. I want a generic editor template.
In your editor template you seem to be using some ViewData["Items"] property which you never set. If you want to use such property make sure you have assigned it:
#Html.EditorFor(
model => model.FaultTypeID,
"RadioButtonList",
new { Items = new SelectList(Model.AllowdeFaultTypes, "FaultTypeID", "FaultTypeName") }
)
This being said, your approach with using some ViewData stuff seems totally wrong to me.
I would simply define a view model (as always in ASP.NET MVC):
public class RadioListViewModel
{
public string Value { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
and then you could have your editor template strongly typed to this view model. Of course your editor template will be now stored in ~/Views/Shared/EditorTemplates/RadioListViewModel.cshtml:
#model IRadioListViewModel
#foreach (var item in Model)
{
<a>#item.Text</a> <b>#item.Value</b>
}
and now all that's left is to use this view model in your main view model:
public class MyViewModel
{
public RadioListViewModel FaultTypes { get; set; }
...
}
and then inside your view simply render the corresponding editor template:
#model MyViewModel
...
#Html.EditorFor(x => x.FaultTypes)
Simple, conventional, strongly typed.
I need to pass multiple data ( probably 2 Html.DropDownList's selected values ) to MVC controller action method from MVC View ( .aspx). I think it would be from somehow Html.Hidden form , but how?
I am unable to get the selected value from Html.DropDownList and pass it as Html.Hidden("paramName", MvcStringSelectedValue) to controller's action.
My Code is :
based on<br />
<%: Html.DropDownList("Semester")%>
<%= Html.Hidden("strSemesterToBaseOn",returnedValueFromAbove)%>
<%: Html.ValidationSummary(true) %>
<input type="submit" value="Clone" />
<% } %>
<br/><br/>
Do I need to write the input tag of "submitt" 2 times or just only once?
Edit ( EXTRA CODE )
Controller's action method :
[HttpPost]
public ActionResult CloneSemesterData(string strSemesterToOrganize, string strSemesterToBaseOn)
{
.............................................................
..............................
}
HERE ( another Controller's method ) IS THE DROP DOWN LIST Filled with Semester values
public ActionResult DepartmentAdministration()
{
// Get list of semesters
var lr = new ListRepository();
ViewData["Semester"] = new SelectList(lr.ListSemester(3)); //this ListSemester(3) will generate the list with 3 strings ( e.g "WS 2012", "SS2010")
return View();
}
My View code in .aspx file is :
//this executes when radioButton ="Clone" is selected
<% using (Html.BeginForm("CloneSemesterData", "CourseNeededHours"))
{%>
<%= Html.DropDownList("Semester")%> // this is First drop down list box , from which selected value , I want to transfer as 1st parameter of controller's action method
<%: Html.ValidationSummary(true) %>
based On
<%= Html.DropDownList("Semester")%> //this is Second drop down list box, from which selected value, I want to transfer as 2nd parameter of controller's action method.
<input type="submit" value="Clone" />
<% } %>
ERROR:
Now, after fixing using Edit 2 : it is giving red lines under
as it is somehow not recognizing the ViewData["SemesterList"]...
"System.Web.Mvc.HtmlHelper does not contain a definition for 'DropDownList' and the best extension method overloaded 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string,System.Collections.Generic.IEnumerable') has some invalid arguments".
Hope now it will clear, still ambiguity , do let me know then.
Regards
Usman
I am not really sure what you're asking here. You don't need any kind of hidden field to post the selected values of a dropdown. Your Dropdownlist code is invalid to begin with.
Typically you have something like this:
<%= Html.DropDownList("SemesterToOrganize", GetSemesterToOrganize()) %>
<%= Html.DropDownList("SemesterToBaseOn", GetSemesterToBaseOn()) %>
And in your controller:
[HttpPost]
public ActionResult MyAction(string SemesterToOrganize, string SemesterToBaseOn) {
// your code.
}
EDIT:
Based on what you've told us. You are relying on the behavior of MVC of populating the DropDownList because you are adding your list to the ViewData with the same name as your dropdownlist. This won't work for you. You will have to populate each dropdown list seperately.
In your controller, do something like this:
public ActionResult MyAction ()
{
ViewData["SemesterList"] = // list of semesters
return View();
}
Then, in your view you have:
<%= Html.DropDownList("SemesterToOrganize", ViewData["SemesterList"]) %>
<%= Html.DropDownList("SemesterToBaseOn", ViewData["SemesterList"]) %>
then your post method
[HttpPost]
public ActionResult MyAction(string SemesterToOrganize, string SemesterToBaseOn) {
// your code.
}
If you want to continue to argue that you can do it your way, then you won't solve your problem. Each dropdown must have it's own unique id, otherwise it will not post correctly. The only way to solve this problem is to give each it's own unique id. That breaks the behavior of the drop down automatically getting the data, so you MUST specify the list of data explicitly.
So stop arguing that this is an unimportant part of the problem. It's not. It's key to the problem.
EDIT2:
Based on your code above:
<%= Html.DropDownList("strSemesterToOrganize", (SelectList)ViewData["Semester"]) %>
<%= Html.DropDownList("strSemesterToBaseOn", (SelectList)ViewData["Semester"]) %>
That's all you need
If you had just given us this, and didn't argue, this would been solved a lot easier.
// Try this. Change names and put in the appropriate namespace.
//Your view
#model MvcApplication2.Models.CloneSemesterDataViewModel
#Html.LabelFor(x => x.SemesterToOrganize)
#Html.DropDownListFor(x => x.SemesterToOrganize, Model.ListofSemestersToOrganize)
--------
#Html.LabelFor(x => x.SemesterToBaseOn)
#Html.DropDownListFor(x => x.SemesterToBaseOn, Model.ListofSemestersToBaseOn)
//view model
namespace MvcApplication2.Models
{
public class CloneSemesterDataViewModel
{
public string SemesterToOrganize { get; set; }
public IEnumerable<SelectListItem> ListofSemestersToOrganize
{
get
{
return new List<SelectListItem> { new SelectListItem { Text = "SS2012" , Value = "SS2012"} };
}
}
public string SemesterToBaseOn { get; set; }
public IEnumerable<SelectListItem> ListofSemestersToBaseOn
{
get
{
return new List<SelectListItem> { new SelectListItem { Text = "SS2012", Value = "SS2012" } };
}
}
}
}
----------
Controller.
[HttpPost]
public ActionResult CloneSemesterData(CloneSemesterDataViewModel viewModel)
{
//viewModel.SemesterToBaseOn
//viewModel.SemesterToOrganize
}
// This should do the trick.
let me ask the question first.
Where is the correct place to call a function that load a list of values to be display on a view?
I create a controller like this
public ActionResult Create()
{
SeaModel newSea = new SeaModel();
return View("Season/CreateSea", newSea);
}
//I not quite sure if this should go here or in another place
partial class seaDataContext
{
public List<string> getSeaSettings()
{
var seaSettings = from p in settings
where p.setting == "periods"
select p.value;
return seaSettings.ToList<string>();
}
}
The model is like
public class SeaModel
{
[Required(ErrorMessage="*")]
[Display(Name = "Period Name")]
public string periods { get; set; }
}
Which create a view like
#using (Html.BeginForm()) {
#Html.ValidationSummary(true, "Please correct the following errors.")
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
#Html.LabelFor(model => model.periods)
</div>
<div class="editor-field">
#Html.Select(model => model.periods, ****My doubt comes here****)
#Html.ValidationMessageFor(model => model.periods)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
so, How and where do I pass the return of getSeaSettings() to the view?
Thanks
best practice is to make a Selectlist in your Model for this dropdown.
however you also can use the more easy option: using ViewData
public ActionResult Create()
{
SeaModel newSea = new SeaModel();
ViewData["myDropDown"] = new SelectList(listOfObjects, "valueOfTheObjectLikeID", "NameYouWantToShowInDropdown");
return View("Season/CreateSea", newSea);
}
then:
#Html.Select(model => model.periods, ViewData["myDropDown"] as SelectList)
dont forget in your [HttpPost] method to also fill in the viewdata if you'r validation fails, so the dropdown can be rebuilt.
You need to look at repository pattern. Have a look at this tutorial at asp.net site
http://www.asp.net/mvc/tutorials/creating-model-classes-with-linq-to-sql-cs
Stefanvds's approach was what I used to do.
But I found out there is a better way using additionalViewData.
Use this EditorFor HTML Helper extension method.
http://msdn.microsoft.com/en-us/library/ff406462.aspx
Instead of passing Select List Items into ViewData in the Controller, you do this in your View.
Pass in your list items as an anonymous object for the additionalViewData parameter.
Important thing is to use the same name as your Property Name.
#Html.EditorFor(
m => m.MyPropertyName,
new { MyPropertyName = Model.ListItemsForMyPropertyName }
);
Of course, you are passing in a View Model object.
public class MyViewModel
{
public int MyPropertyName;
public IList<SelectListItem> ListItemsForMyPropertyName;
}
EditorFor method uses your existing Editor View Templates.
So you don't need to specify CSS class names and HTML attributes again like when you use the Html.DropDown( ) method.
For example,
//------------------------------
// additionalViewData
//------------------------------
#Html.EditorFor(
m => m.MyPropertyName,
new { MyPropertyName = Model.ListItemsForMyPropertyName }
)
//------------------------------
// traditional approach requires to pass your own HTML attributes
//------------------------------
#Html.DropDown(
"MyPropertyName",
Model.ListItemsForMyPropertyName,
new Dictionary<string, object> {
{ "class", "myDropDownCssClass" }
}
);
//------------------------------
// DropDownListFor still requires you to pass in your own HTML attributes
//------------------------------
#Html.DropDownListFor(
m => m.MyPropertyName,
Model.ListItemsForMyPropertyName,
new Dictionary<string, object> {
{ "class", "myDropDownCssClass" }
}
);
That is why I like the additionalViewData approach more.
Because, the HTML code rendered relies on the Editor Templates completely.
Also, using specialized View Models make your code cleaner and easier to maintain.
Hope it helps.
ASP.NET MVC Model Binding is still new to me and I'm trying to understand exactly how it works. Right now, I appear to be having problems with a feature of Html.Textbox()
Specifically, I have a View where I set Html.Textbox to a value both in the "Get" and the "Post". It sets fine in the "Get", but after the user submits a value during the "Post", I have the class change one of the values internally based on the other value submitted.
(I'm basically validating one value based on the other... I'm not sure if this is the right way to do this...)
Tracing through, I can see that the value has actually changed as expected both in the Model and in the View, but when it displays on my screen after the "Post", the value does not display as it was changed. Instead it is what it was set to originally.
Here's my simplified example:
The View shows a:
Drop-down with items from a SelectList (pre-selected as "Other")
a Read-only Text Box (with a pre-loaded value of 0)
Submit Button
User should pick a new value from the Drop-Down and click submit. The "Post" method in the controller picks up the new value from the Drop-Down and changes the Value in the Read-only text-box and re-displays.
(Yes, I'll eventually be doing this with JQuery, too...)
Here's my sample Model class:
public class SampleSubmission
{
public string Name { get; set; }
public int Volume { get; set; }
public readonly SortedList<string, int> NameVolumeList = new SortedList<string, int>();
// Standard Constructor
public SampleSubmission()
{
NameVolumeList.Add("Sample1", 10);
NameVolumeList.Add("Sample2", 20);
NameVolumeList.Add("Sample3", 50);
NameVolumeList.Add("Other", 0);
this.Name = NameVolumeList.Keys[0];
this.Volume = NameVolumeList[Name];
}
// Copy Constructor
public SampleSubmission(SampleSubmission samSub) : this()
{
this.Name = samSub.Name;
this.Volume = NameVolumeList[Name];
}
}
Here's the Controller:
public class SampleSubmissionController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
SampleSubmission sampleSub = new SampleSubmission();
return View(sampleSub);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SampleSubmission sampleSub)
{
SampleSubmission samSub = new SampleSubmission(sampleSub);
return View(samSub);
}
}
Here's the View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcModelBindTest.Models.SampleSubmission>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("Name", new SelectList(Model.NameVolumeList.Keys.ToList())) %>
<%= Html.TextBox("Volume",Model.Volume) %>
<input type="submit" name="pick" id="pick" value="Pick" /> <% } %>
</asp:Content>
Any ideas as to why the new value does not display?
EDIT:
In order to fix the problem, I read the link given by "jfar" and made a 1-line change.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SampleSubmission sampleSub)
{
SampleSubmission samSub = new SampleSubmission(sampleSub);
// Reset Model Value
ModelState.SetModelValue("Volume", new ValueProviderResult(
samSub.Volume, "", System.Globalization.CultureInfo.CurrentCulture));
return View(samSub);
}
This definitely works. Unfortunately, this feels like a gross hack to me. What if I had to update the values of multiple fields? There must be a better (simpler?) way of doing this.
EDIT2: Found my answer. See below...
From: How to clear textboxes defined with MVC HTML helpers
"The HTMLHelper's first look at the
ModelState and ViewData to see if any
values match their key and then
finally use whatever value you provide
them.
If you need to reset the textboxe's
value you also need to clear the
ModelState entry with the matching
key. Another alternative is
redirecting to the same page instead
of simply rendering a view via
javascript or with MVC.
I figured out the answer to my own question when I stumbled upon another variable that needed to be reset. As I was looking at the data structure, I realized what I wanted was the pristine state where there were no Keys in the ModelState.
ModelState.Remove(key);
Where "key" is the value you're trying to reset.
Another simple workaround is instead of
<%= Html.TextBox("Volume",Model.Volume) %>
Use HTML input tag
<input id="Volume" name ="Volume" value="#Model.Volume" />