How does ASP.NET MVC repopulate values in form when validation fails? - asp.net

In web forms the view state is used. But in ASP.NET MVC since model binding is available the properties can be easily acccessed in the controller. However when the model validation fails, does the ASP.NET MVC automatically populate the form controls realising that the validation has failed?
Or is there any other way by which this is accomplished.

There is an property called ModelState (in Controller class), that holds all the values. It is used in model binding. When validation fails, ModelState holds all the values with validation errors.
ModelState.IsValid tells you, that validation didn't throw any errors.
ModelState.Values holds all the values and errors.
EDIT
Example for Ufuk:
View model:
public class EmployeeVM
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Actions:
[HttpGet]
public ActionResult CreateEmployee()
{
return View();
}
[HttpPost]
public ActionResult CreateEmployee(EmployeeVM model)
{
model.FirstName = "AAAAAA";
model.LastName = "BBBBBB";
return View(model);
}
View:
#model MvcApplication1.Models.EmployeeVM
#using (Html.BeginForm("CreateEmployee", "Home")) {
#Html.EditorFor(m => m)
<input type="submit" value="Save"/>
}
As you can see, in POST method values are overwritten with AAAAA and BBBBB, but after POST, form still displays posted values. They are taken from ModelState.

Related

Entering Value in Partial View and Posting it back to Main Controller in ASP.NET MVC 5 [duplicate]

I have a ViewModel that has a complex object as one of its members. The complex object has 4 properties (all strings). I'm trying to create a re-usable partial view where I can pass in the complex object and have it generate the html with html helpers for its properties. That's all working great. However, when I submit the form, the model binder isn't mapping the values back to the ViewModel's member so I don't get anything back on the server side. How can I read the values a user types into the html helpers for the complex object.
ViewModel
public class MyViewModel
{
public string SomeProperty { get; set; }
public MyComplexModel ComplexModel { get; set; }
}
MyComplexModel
public class MyComplexModel
{
public int id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
....
}
Controller
public class MyController : Controller
{
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.ComplexModel = new MyComplexModel();
model.ComplexModel.id = 15;
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// model here never has my nested model populated in the partial view
return View(model);
}
}
View
#using(Html.BeginForm("Index", "MyController", FormMethod.Post))
{
....
#Html.Partial("MyPartialView", Model.ComplexModel)
}
Partial View
#model my.path.to.namespace.MyComplexModel
#Html.TextBoxFor(m => m.Name)
...
how can I bind this data on form submission so that the parent model contains the data entered on the web form from the partial view?
thanks
EDIT: I've figured out that I need to prepend "ComplexModel." to all of my control's names in the partial view (textboxes) so that it maps to the nested object, but I can't pass the ViewModel type to the partial view to get that extra layer because it needs to be generic to accept several ViewModel types. I could just rewrite the name attribute with javascript, but that seems overly ghetto to me. How else can I do this?
EDIT 2: I can statically set the name attribute with new { Name="ComplexModel.Name" } so I think I'm in business unless someone has a better method?
You can pass the prefix to the partial using
#Html.Partial("MyPartialView", Model.ComplexModel,
new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "ComplexModel" }})
which will perpend the prefix to you controls name attribute so that <input name="Name" ../> will become <input name="ComplexModel.Name" ../> and correctly bind to typeof MyViewModel on post back
Edit
To make it a little easier, you can encapsulate this in a html helper
public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
{
string name = ExpressionHelper.GetExpressionText(expression);
object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new System.Web.Mvc.TemplateInfo
{
HtmlFieldPrefix = string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix) ?
name : $"{helper.ViewData.TemplateInfo.HtmlFieldPrefix}.{name}"
}
};
return helper.Partial(partialViewName, model, viewData);
}
and use it as
#Html.PartialFor(m => m.ComplexModel, "MyPartialView")
If you use tag helpers, the partial tag helper accepts a for attribute, which does what you expect.
<partial name="MyPartialView" for="ComplexModel" />
Using the for attribute, rather than the typical model attribute, will cause all of the form fields within the partial to be named with the ComplexModel. prefix.
You can try passing the ViewModel to the partial.
#model my.path.to.namespace.MyViewModel
#Html.TextBoxFor(m => m.ComplexModel.Name)
Edit
You can create a base model and push the complex model in there and pass the based model to the partial.
public class MyViewModel :BaseModel
{
public string SomeProperty { get; set; }
}
public class MyViewModel2 :BaseModel
{
public string SomeProperty2 { get; set; }
}
public class BaseModel
{
public MyComplexModel ComplexModel { get; set; }
}
public class MyComplexModel
{
public int id { get; set; }
public string Name { get; set; }
...
}
Then your partial will be like below :
#model my.path.to.namespace.BaseModel
#Html.TextBoxFor(m => m.ComplexModel.Name)
If this is not an acceptable solution, you may have to think in terms of overriding the model binder. You can read about that here.
I came across the same situation and with the help of such informative posts changed my partial code to have prefix on generated in input elements generated by partial view
I have used Html.partial helper giving partialview name and object of ModelType and an instance of ViewDataDictionary object with Html Field Prefix to constructor of Html.partial.
This results in GET request of "xyz url" of "Main view" and rendering partial view inside it with input elements generated with prefix e.g. earlier Name="Title" now becomes Name="MySubType.Title" in respective HTML element and same for rest of the form input elements.
The problem occurred when POST request is made to "xyz url", expecting the Form which is filled in gets saved in to my database. But the MVC Modelbinder didn't bind my POSTed model data with form values filled in and also ModelState is also lost. The model in viewdata was also coming to null.
Finally I tried to update model data in Posted form using TryUppdateModel method which takes model instance and html prefix which was passed earlier to partial view,and can see now model is bound with values and model state is also present.
Please let me know if this approach is fine or bit diversified!

MVC ViewModel returns ArgumentNullException

I am having a problem returning values to the controller when using a ViewModel.
For clarity I have simplified the code below where the original has many more fields.
When the page is loaded, the value in the hidden field is as expected. However when the form is submitted the value in the field is not being sent and instead I get an ArgumentNullException.
Please can you advise on what I am doing wrong.
View
#model Project.Models.SCView
#using (Html.BeginForm("ScorecardEdit"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.FV.ID)
<input type="submit" value="Save" />
}
Model
public class FixView
{
public int ID { get; set; }
[DisplayFormat(DataFormatString = "{0:ddd dd/MM/yyyy}")]
public DateTime MatchDate { get; set; }
}
public class SCView
{
public FixView FV { get; set; }
public SCView()
{
this.FV = new FixView();
}
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ScorecardEdit(SCView ReturnSC)
{
}
The code that you have should be working as MVC should be able to map your FV.ID property as expected as the HiddenFor() helper will generate the proper names to handle mapping it :
Using the same code that you provided, the debugger demonstrated the following after submitting the form :
The issue here sounds like you have a few other properties, possibly collection-based ones that use the DropDownListFor() helpers that have collections which are not posted to the server, so when you attempt to use the model you have to render populate one of those helpers, you are getting your ArgumentNullException.

MVC 4 Action Result er

I am new in Asp.net MVC 4
I write function using MVC controller
public ActionResultRole_name(string role)
{
return role;
}
My question is how to display return value on cshtml razor view?
You could return a ViewResult:
public ActionResult Role_name(string role)
{
return View((object)role);
}
and in the corresponding Role_name.cshtml view you could use this value:
#model string
<div>The role is #Model</div>
Notice how it was necessary to cast the role variable to an object to ensure that the proper View method overload (taking a model) is being resolved.
On the other hand you could have used a view model which is always best practice:
public class MyViewModel
{
public string Role { get; set; }
}
which your controller action could have populated and passed to the corresponding stringly typed view:
public ActionResult Role_name(string role)
{
var model = new MyViewModel();
model.Role = role;
return View(model);
}
and in the view:
#model MyViewModel
<div>The role is #Model.Role</div>
Also I would recommend you taking a look at some of the getting started tutorials on the asp.net/mvc site.

ASP.NET MVC3: can Action accept mulitple model parameters?

For example:
class MyContoller
{
[MyCustomAttribute]
public ActionResult MyAction(ModelX fromRequest, ModelY fromSession, ModelZ fromCookie)
{
string productId = fromRequest.ProductId;
string userId = fromSession.UserId;
string cultureName = fromCookie.CultureName;
}
}
Reason:
I don't want to visit Request, Session and HttpContext in the controllers, and the default idea of MVC3 which passing models to actions is very great.
I want the number of parameters of MyAction is easy to change. For example, if I add a new parameter, the system will try to look for values in Request, Session or Cookies by the name or type of the parameter (I think custom ModelBinders may be required for cookie values) and pass the filled model to my action. I don't have to write extra code.
Can the custom attribute (MyCustomAttribute in the example) accomplish this idea?
I am not sure I follow you about the custom attribute. What are you expecting the custom attribute to do?
Yes, an action method can take as many model parameters as you want. Obviously, only one can be bound in any given request (because a view can only have one model). Whichever one is found first will be bound, and the others will be null.
So let's say you have the following:
public class ModelX {
public string X {get;set;}
}
public class ModelY {
public string Y {get;set;}
}
public class ModelZ {
public string Z {get;set;}
}
And you have an action method like this:
public ActionResult DoIt(ModelX x, ModelY y, ModelZ z)
{
return View();
}
And in your DoIt.cshtml you have the following:
#model ModelZ
#using(Html.BeginForm()) {
#Html.TextBoxFor(x => x.Z)
<input type="submit"/>
}
If you type something into the textbox and submit, then the model binder will bind a ModelZ with the value you entered and ModelX and ModelY will be null.
If you mean can an action method bind multiple models simultaneously, then I would have to ask you.. How exactly do you plan to have a view have more than one model? You can certainly create a wrapper model to contain the multiple models, but a view can only have one.
Create a composite ViewModel class that incorporates ModelX, ModelY and ModelZ. You can then populate an instance of your new ViewModel class, and pass that to your controller method.
public class XYZViewModel
{
public ModelX fromRequest { get; set; }
public ModelY fromSession { get; set; }
public ModelZ fromCookie { get; set; }
}
public class MyController
{
[MyCustomAttribute]
public ActionResult MyAction(XYZViewModel myModel)
{
string productId = myModel.fromRequest.ProductId;
string userId = myModel.fromSession.UserId;
string cultureName = myModel.fromCookie.CultureName;
}
}
You can always pass multiple parameters to your controller action, yes. The key is to make sure they are properly serialized in the request. If you're using a form, that means using the Html helper methods.
For example, let's say you want an action like this:
public ActionResult Multiple(ModelA a, ModelB b)
{
// ...
}
You could create simple partial view for each model:
#model MyProject.Models.ModelA
#Html.EditorForModel()
Then in your Multiple view, render the partial views like so:
#{ using (Html.BeginForm("Multiple", "MyController", FormMethod.Get))
{
#Html.Partial("A", new MyProject.Models.ModelA())
#Html.Partial("B", new MyProject.Models.ModelB())
<input type='submit' value='submit' />
}
I set the method to GET here so that you can easily see how MVC passes the parameters. If you submit the form, you'll see that MVC successfully deserializes each object.

How do I repopulate the view model in ASP.NET MVC 2 after a validation error?

I'm using ASP.NET MVC 2 and here's the issue. My View Model looks something like this. It includes some fields which are edited by the user and others which are used for display purposes. Here's a simple version
public class MyModel
{
public decimal Price { get; set; } // for view purpose only
[Required(ErrorMessage="Name Required")]
public string Name { get; set; }
}
The controller looks something like this:
public ActionResult Start(MyModel rec)
{
if (ModelState.IsValid)
{
Repository.SaveModel(rec);
return RedirectToAction("NextPage");
}
else
{
// validation error
return View(rec);
}
}
The issue is when there's a validation error and I call View(rec), I'm not sure the best way to populate my view model with the values that are displayed only.
The old way of doing it, where I pass in a form collection, I would do something like this:
public ActionResult Start(FormCollection collection)
{
var rec = Repository.LoadModel();
UpdateModel(rec);
if (ModelState.IsValid)
{
Repository.SaveModel(rec);
return RedirectToAction("NextPage");
}
else
{
// validation error
return View(rec);
}
}
But doing this, I get an error on UpdateModel(rec): The model of type 'MyModel' could not be updated.
Any ideas?
I figured this one out. If you call UpdateModel and there's a validation error, it's going to throw an exception. The way around this is call TryUpdateModel instead.
Your Price member setter (probably) shouldn't be public, you may want to consider loading the price from where ever it's stored in the model.
The other thing would be when rendering the view don't render the Price with a text box (or other input type).
public class MyModel
{
public decimal Price
{
get
{
return //get the value from something
}
} // for view purpose only
[Required(ErrorMessage="Name Required")]
public string Name { get; set; }
}
Using a strong type View
If you' use a strong type view this should work out of the box:
ViewPage<MyModel>
Your fields should be displayed as:
<%= Html.TextBoxFor(m => m.Name) %>
You shouldn't display read-only properties in editable fields anyway. When you'd redisplay the invalid view and providing the passed in model object instance in your controller action, your values should be populated in your textbox (or string only containers) as expected.
I don't think you should have any problems with Price property this way, but just in case have you tried using this controller action declaration:
public ActionResult Start([Bind(Exclude = "Price")]MyModel rec)
{
// ...
}

Resources