When are model objects created in MVC3 (ASP.NET) - asp.net-mvc-3

Trying to understand when model objects are instantiated in MVC3:
I have a view for editing a "Person"; each person can have multiple addresses. I'm displaying the addresses in a grid on the Person View.
This works great when displaying a person; I have a partial view which iterates through Person.Addresses and builds the table/grid.
The problem arises when creating a new person: the person object is null and the Person.Addresses reference is illegal.
I'm certain I'm missing something fairly fundamental here: since MVC will be (auto-magically) creating the new person instance upon "Save"; it would seem counter-production to try and create my own object instance, and if I did, it is unclear how I would connect it to the rest of the entry values on the form.
One last complications: the list of Addresses is optional; it is perfectly legal not to have an address at all.
As relational data is so common, there has to be a simpler solution for handling this. All clarifications appreciated!

The answer to this question is that the objects are re-constituted from the POST data in the form. This is fairly basic, but MVC hides so much of what is happening that it is hard to see when you are trying to get your (MVC) bearings.
The sequence of items is:
Create form with all necessary fields; use hidden fields for non-displayed keys (ID).
User interacts with web page; then presses form submit button.
All field data is POSTed to the controller page.
MVC re-constitutes the data into class objects.
The controller page is invoked with the re-constituted class instance as a formal parameter.
Notes:
When creating the page: a form is generated with fields for each part of the object being represented. MVC uses hidden fields for ID's and other non-displayed data as well as for validation rules.
It is worth noting that forms are created (typically) either by listing all object properties on the _CreateOrEdit.cshtml page:
// Edit.cshtml
#model Person
#Html.Partial("_CreateOrEdit", Model)
and
// _CreateOrEdit.cshtml
#model Person
#Html.HiddenFor(model => model.PersonID)
#Html.LabelFor(model => model.first_name, "First Name")
#Html.EditorFor(model => model.first_name)
#Html.LabelFor(model => model.last_name, "Last Name")
#Html.EditorFor(model => model.last_name)
#Html.LabelFor(model => model.favorite_color, "Favorite Color")
#Html.EditorFor(model => model.favorite_color)
//etcetera
or by using a template for the class (templates must have the same name as the class they represent and they are located in the Views\Shared\EditorTemplates folder).
Using template pages is almost identical to the previous method:
// Edit.cshtml
#model Person
#Html.EditorForModel()
and
// Shared\EditorTemplates\Person.cshtml
#model Person
#Html.HiddenFor(model => model.PersonID)
#Html.LabelFor(model => model.first_name, "First Name")
#Html.EditorFor(model => model.first_name)
#Html.LabelFor(model => model.last_name, "Last Name")
#Html.EditorFor(model => model.last_name)
#Html.LabelFor(model => model.favorite_color, "Favorite Color")
#Html.EditorFor(model => model.favorite_color)
//etcetera
Using the template method makes it easy to add lists (of object) to the form. Person.cshtml becomes:
// Shared\EditorTemplates\Person.cshtml
#model Person
#Html.HiddenFor(model => model.PersonID)
#Html.LabelFor(model => model.first_name, "First Name")
#Html.EditorFor(model => model.first_name)
#Html.LabelFor(model => model.last_name, "Last Name")
#Html.EditorFor(model => model.last_name)
#Html.LabelFor(model => model.favorite_color, "Favorite Color")
#Html.EditorFor(model => model.favorite_color)
#EditorFor( model => model.Addresses )
//etcetera
and
// Shared\EditorTemplates\Address.cshtml
#model Address
#Html.HiddenFor(model => model.AddressID)
#Html.LabelFor(model => model.street, "Street")
#Html.EditorFor(model => model.street)
#Html.LabelFor(model => model.city, "City")
#Html.EditorFor(model => model.city)
//etcetera
MVC will handle creating as many form entries as necessary for each address in the list.
The POST works exactly in reverse; a new instance of the model object is created, calling the default parameter-less constructor, and then MVC fills in each of the fields. Lists are populating by reversing the serialization process of #Html.EditorFor( model.List ). It is important to note that you must make certain your class creates a valid container for the list in the constructor otherwise MVC's list re-constitution will fail:
public class Person
{
public List<Address> Addresses;
public Person()
{
// You always need to create this List object
Addresses = new List<Address>();
}
...
}
That cover's it. There is a lot going on behind the scenes, but it is all track-able.
Two important points if you are having trouble with this:
Make sure you have #Html.HiddenFor(...) for everything that needs to "survive" the trip back to the server.
Use Fiddler or HTTPLiveHeaders (Firefox plug-in) to examine the contents of the POST data. This will let you validate what data is being sent back to re-constitute the new class instance. I'm partial to Fiddler since you can use it with any browser (and it shows form data particularly well).
One last point: there is a good article on dynamically adding / removing elements from a list with MVC: http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3 It's a good article to work through -- and yes, it does work with MVC3 and Razor.

The addresses I'm assuming are in a table, not actual input elements and likely just <td>info</td>?
If so, then they won't get instantiated as there is no data being posted back to the server.
You must have this data being created with elements that are posted back in order to have them mapped (by name) to their properties. The model binder will instantiate the objects and pass them to your controller upon postback if it can find appropriately named posted form (or querystring) elements.

Related

What's the proper way to add a form to the Index page that posts to the Create action, including validation?

I have an Index view in my application that shows a list of vendors. I also want to add a small form to add new items right on that page. The create form will post to the Create action. My model class contains a list of vendors, plus one property for a single vendor named NewVendor.
public IEnumerable<SoftwareVendor> Vendors { get; set; }
public SoftwareVendor NewVendor { get; set; }
The SoftwareVendor class has validation attributes. It's an Entity Framework class.
Making a form that posts to the Create action is easy:
#using (Html.BeginForm( "Create", "Vendor" )) {
#Html.ValidationSummary(true)
<fieldset>
<legend>New Software Vendor</legend>
<div class="editor-label">
#Html.LabelFor(model => model.NewVendor.Name)
</div>
<div class="editor-field">
#Html.EditorFor( model => model.NewVendor.Name )
#Html.ValidationMessageFor( model => model.NewVendor.Name )
</div>
<br />
<input type="submit" value="Create" />
</fieldset>
}
This posts just fine, and client-side validation also works. However, the default Create action takes an instance of SoftwareVendor and is looking for a key in the form collection called "Name". Instead, the above form posts "NewVendor.Name".
I can remedy this by specifying a template and field name in #Html.EditorFor.
#Html.EditorFor( model => model.NewVendor.Name, "string", "Name" )
Now the Create action is happy because the "Name" value is being received. However, the validation message is broken because it is still looking for a field named "NewVendor.Name", and there seems to be no way to override this.
<span class="field-validation-valid" data-valmsg-for="NewVendor.Name" data-valmsg-replace="true"></span>
Is there something simple I'm missing to make this work?
Here is a list of things I can do to solve this:
Have my Create action take an instance of my Index model instead of a SoftwareVendor. I still have a traditional Create view, though, and I don't want to do this.
Don't have my Create action take any parameters. Instead, manually look at the form keys and pull the name from either "Name" or "NewVendor.Name", whichever is there.
Have the Create action take both model classes and detect which one got populated properly. This is a lot like #2 but I'm checking properties for non-null values instead of checking the form collection.
Figure out how to make a model binder that will perform what #2 is doing. This seems overly complicated, and I'm going to have this problem in a number of pages, so I'm hoping for an easier way.
Use javascript to make the post instead of a form submit, so I can control the exact field names I'm posting. This works, but I'd prefer to leverage an HTML form, since that's what it's for.
Use the overload of EditorFor to specify the field name, and create the validation message manually.
Write my own extension method on HtmlHelper for a new ValidationMessageFor that can override the field name.
Of these options, #2 or #5 are the ones I think I'd choose from unless there's a better way.
Well, this worked:
#Html.EditorFor( model => model.NewVendor.Name, "string", "Name" )
#Html.ValidationMessage( "Name" )
Since my only real problem with my above code was a broken validation message, this seems to solve my problem. I'm still curious if there is a better solution overall.

ASP.NET MVC3 passing data between primary view and a search view via Ajax link

I have just started learning ASP.NET MVC3.
I have the following scenario. In a create view for a certain model the user can lookup code/description by clicking on a link (rendered with Html.ActionLink helpers). The lookup values are retrieved from lookup tables in a database and presented in a separate view. The two views are handled by two different controllers. When the user selects a lookup value in the latter view that value (code+description) should be copied back to the create view.
How can data be passed between the two views? Is this not possible due to the stateless nature of Http requests?
I tried that with an Ajax link, but it didn't worked out.
code snippet Create view:
<fieldset>
<legend>Z-Info</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ZZL_U_CODE)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ZZL_U_CODE)
#Html.ValidationMessageFor(model => model.ZZL_U_CODE)
</div>
<div class="editor-label">
#Ajax.ActionLink("Land code test", "Index", "Domein", new {name = "lan" },
new AjaxOptions {
HttpMethod = "Get",
Url = Url.Action("Index", "Domein", new {name = "lan" }),
OnBegin = "OnBegin",
OnSuccess = "InsertCodeNaam",
OnFailure = "OnFailure",
OnComplete = "OnComplete"
})
</div>
When the user select a code/description the following Select action is called which returns Json data back.
Select action:
public class DomeinController : Controller
{
private ZZLEntities db = new ZZLEntities();
//
// GET: /Domein/
public ViewResult Index(string name)
{
DomeinViewModel model = DomeinRepositry.GetAll(name);
return View(model);
}
GET: /Domein/Select/5
public JsonResult Select(int id, string naam)
{
return Json(new DomCodeNaam { codeValue = id, naamValue = naam }, JsonRequestBehavior.AllowGet);
}
Are there other solutions possible? Can partial views be an option?
Well you have two options:
Just post back lookup values and then internally redirect to the
first ("create") view, but this time passing (internally) the values
chosen by user so the view can be rendered with chosen values. Maybe
not fancy but very easy to implement. You will loose data that user have already entered into first form though, unless you post it too or you make this a 2 step process.
If you want to use Ajax, you need update appropriate parts of the
form in the first "create" view on the client side, depending on the
actions of user (i.e. what lookup values they have chosen).
I am however a bit confused with what you exactly mean by "separate view"

ModelState validation errors for properties that are not present in my view

Suppose this view :
#Html.HiddenFor(model => model.Batiment.Client.Id)
#Html.LabelFor(model => model.Batiment.Code)</td>
#Html.EditorFor(model => model.Batiment.Code)</td>
<br>
#Html.LabelFor(model => model.Batiment.Nom)</td>
#Html.EditorFor(model => model.Batiment.Nom)</td>
When I submit my form on the controler the ModelState is invalid for the property "Nom" required into my class Client. Is true, the metadata in my class Client is set to required but I dont include this field into my view...! Why Mvc raise this error?
Can I hide a field (like Id) without specify all the required field into my view?
Errors enter model state during binding, therefore you could exclude your property from binding by including the following in your action method signature:
public ActionResult Register([Bind(Exclude="PropertyName")] UserViewModel user)
{
// Your logic here
}
This should exclude PropertyName from binding, therefore error won't enter your model state and your validation should succeed. Just to add, I think that this is more of a hack, rathern then solution. If you need only a part of your view model, than this view model should not be used and you should really consider creating a new view model without this property.
It might look very similar and it might seem like duplicate code, but it isn't. It promotes seperation of concerns and you should see the benefit of doing this in the near future when it comes to extending/modifying your application.
No, the validation is done on the model, not the view, why it is called 'model state'
You need to create another view for this scenario. This is exactly what ViewModels are for.
Then you can use a tool like AutoMapper to easily to copy the properties between this view model to your base model.

Passing a selected value from a partial view to the main view's viewmodel

As ASP.Net MVC3 newbies we have an issue that would like assistance with. (Questions at the bottom of this thread too.)
First of all I am not sure if the following is the best way to go about this so please let me know if we are heading in the wrong direction. We would like to use partial views to do lookups for dropdown lists. In some cases the lookups will be done in multiple places and also, the data is not part of our viewmodel. The data may be coming from a Database or Web Service in our application. Some of the data is loaded at startup and some is based upon other values selected in the form.
We are calling a child action from our main view and returning a partial view with the data we obtained. Once the user selects their choice we are not sure how to store the selected item code in our main view model.
In our main form we call to an action:
#model Apps.Model.ViewModels.AVMApplicationInfo
...
<div class="editor-label">
#Html.LabelFor(m => m.VMResidencyWTCS.DisplayState)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.VMResidencyWTCS.DisplayState)
#Html.DropDownListFor(m => m.VMResidencyWTCS.DisplayState, Apps.Model.Helpers.ResidencyStates.StateList)
#Html.ValidationMessageFor(m => m.VMResidencyWTCS.DisplayState)
</div>
#Html.Action("DisplayCounties", "PersonalInfo")
...
In the PersonalInfo controller:
[ChildActionOnly]
public ActionResult DisplayCounties()
{
IList<County> countiesDB = _db.Counties
.OrderBy(r => r.CountyDescr)
.Where(r => r.State == "WI"
&& r.Country == "USA")
.ToList();
//Create an instance of the county partial view model
VMCounty countyView = new VMCounty();
//Assign the available counties to the view model
countyView.AvailableCounties = new SelectList(countiesDB, "CountyCd", "CountyDescr");
return PartialView("_DisplayCounties", countyView);
}
In the _DisplayCounties partial view:
#model Apps.Model.ViewModels.VMCounty
<div class="editor-label">
#Html.LabelFor(m => m.CountyDescr)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.SelectedCountyCd, Model.AvailableCounties)
</div>
How do I assign the SelectedCountyCd to a field in the main form view model (Apps.Model.ViewModels.AVMApplicationInfo )? Are there any issues of when the child action/partial view is called; i.e., is it loaded at start up and can this method be used to include a user choice as a filter for the lookup? If so, how could the value be passed to the child controller; viewbag?
You could pass it as parameter to the child action:
#model Apps.Model.ViewModels.AVMApplicationInfo
...
#Html.Action("DisplayCounties", "PersonalInfo", new {
selectedCountyCd = Model.CountyCd // or whatever the property is called
})
and then have the child action take this value as parameter:
[ChildActionOnly]
public ActionResult DisplayCounties(string selectedCountyCd)
{
IList<County> countiesDB = _db.Counties
.OrderBy(r => r.CountyDescr)
.Where(r => r.State == "WI"
&& r.Country == "USA")
.ToList();
//Create an instance of the county partial view model
VMCounty countyView = new VMCounty();
//Assign the available counties to the view model
countyView.AvailableCounties = new SelectList(countiesDB, "CountyCd", "CountyDescr");
// assign the selected value to the one passed as parameter from the main view
countyView.SelectedCountyCd = selectedCountyCd;
return PartialView("_DisplayCounties", countyView);
}

ASP.NET MVC 3 - edit items dynamically added to model collection in jquery dialog

I'm new to MVC, so I wasn't sure what the best approach would be here.
I have a view model that contains several collections like this:
public class MainViewModel{
public List<AViewModel> A { get; set; }
public List<BViewModel> B {get; set; }
...}
I'm using Steve Sanderson's approach here to dynamically add items to a collection, and it's working fine as long as the child items are editable on the main view.
The problem I'm having is returning a read only list with an edit link that will open the details to edit in a popup dialog.
Since these items may be newly added, I can't use the ID property to return a partial view from the controller. It seems like I'll have to render the editors in a hidden div like this:
<div class="AEditorRow">
#using (Html.BeginCollectionItem("A"))
{
#Html.DisplayFor(l => l.ID)
#Html.DisplayFor(l => l.Name)
#Html.DisplayFor(l => l.Code)
edit <text>|</text>
delete
<div class="ADetails" style="display: none">
#using (Html.BeginForm("EditA", "Controller"))
{<fieldset>
<legend>Location</legend>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.Code)
</div>
Does anyone know of a better way to do this?
After working on this issue for a while now I was able to find a walk-through that worked for me.
http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3
I think this is the most applicable technique for accomplishing dynamically added nested collection objects for MVC3. Most of the other suggestions I've found were meant for MVC2 or MVC1, and it seems that every iteration of MVC the best way to accomplish this changes slightly.
Hopefully this works for you.
I have the same question. Now looking for solution.
Seems like this resources can help:
http://www.joe-stevens.com/2011/06/06/editing-and-binding-nested-lists-with-asp-net-mvc-2/
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
Model binding nested collections in ASP.NET MVC

Resources