Can't figure out why model is null on postback? - asp.net-mvc

I'm new to ASP.NET MVC and I'm trying to create a very simple blog type site as a means of learning how everything works. But, I'm having a problem when posting from a comment form to a model which is null and I can't tell why.
On a blog post page, I have an "add comment" link which calls some JQuery to render a partial view that is strongly typed to the CommentModel. The link passes in the ID of the blog post as well and the partial is coded like:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Blog.Models.CommentModel>" %>
<% using (Html.BeginForm())
{ %>
<%: Html.HiddenFor(x => x.Post.ID) %>
<%: Html.HiddenFor(x => x.CommentID) %>
<%: Html.TextBoxFor(x => x.Name) %><br />
<%: Html.TextBoxFor(x => x.Email) %><br />
<%: Html.TextBoxFor(x => x.Website) %><br />
<%: Html.TextAreaFor(x => x.Comment) %><br />
<input type="submit" value="submit" />
<% } %>
The CommentsModel is simple and looks like this (I haven't applied any validation or anything yet):
public class CommentModel
{
public BlogPost Post { get; set; }
public int CommentID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Website { get; set; }
public string Comment { get; set; }
}
This is then supposed to post to a simple controller action which will add the comment to the database and return the user to the page. For the sake of simplicity, I've stripped out most of the code but it looks similar to:
[HttpPost]
public ActionResult CommentForm(CommentModel model)
{
if (ModelState.IsValid)
{
}
else
{
}
}
Everything works as expected, except that when posting the comment form, the comment model is null. I can't figure out why this is null. When I view the source of the rendered partial view, I can see that the "Post.ID" is populated with the correct ID, but this is lost when the form is submitted.
Am I missing something obvious here? I've set up forms similar to this in the past and it's worked fine, I can't understand why its not now. Thanks in advance.
Later Edit:
I had typed the code incorrectly and changed the public ActionResult CommentForm(CommentModel model) from public ActionResult CommentForm(CommentModel comment) which was causing the problem.
Thanks for the help.

Similar kind of question has been answered yesterday. Check out : MVC3 - Insert using ViewModel - Object reference not set to an instance of an object
The problem I can see is , when the form is posted, the Post.ID and CommentID are passed, whereas your action is expecting a full blown object of type "CommentModel". The model binder is unable to map the post data, into the corresponding model object.

Add:
public int PostID {get; set;}
...to your model, and populate that in your controller as a hidden input. The Post object is not going to parse easily.

Related

ASP.NET MVC 5 model validation for non-nullable types (Int32)

I'm working on an ASP.NET MVC 5 application and the project owner is concerned about "under-posting" issues caused by validating non-nullable types (as mentioned in http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html and http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api).
I created a test case to replicate this issue in ASP.NET MVC 5 but without luck.
Model:
public class ContactModel
{
[Required]
public Int32 data1 { get; set; }
public Int32 data2 { get; set; }
}
View:
<div class="form-group">
#Html.LabelFor(model => model.data1)
<div>
#Html.EditorFor(model => model.data1)
</div>
</div>
<div>
#Html.LabelFor(model => model.data2)
<div>
#Html.EditorFor(model => model.data2)
</div>
</div>
Controller:
public ActionResult Index(Models.ContactModel contact)
{
if (ModelState.IsValid)
{
Response.Write("modelstate is valid<br>");
return View();
}
else
{
Response.Write("modelstate is invalid<br>");
return View();
}
}
It seems that when data1 and data2 are null in the post, their values in the model (contact) will be 0. However, ModelState.IsValid will also be false (instead of true as shown in the two articles).
What I have:
What the second article showed:
I couldn't find any information regarding changes on how model validation works in ASP.NET MVC, so I'm guessing I did something wrong with my test case. Any thought and suggestion are appreciated.
The reason your ModelState is false is because the post is providing form values from each property in your model. Essentially the Model binding system is checking the validity of both data1 and data2 fields as you have #Html.EditorFor helpers explicitly written for both properties in your view (so no underposting is actually going on).
I did successfully replicate the under-posting concerns from the articles. Simply remove one of the EditorFor helpers in your view, so you're actually underposting. With both helpers present, there's no underposting going on. So the view looks like this now (note I added the validation helper for both properties to get feedback in the view on what's going on):
View:
<div class="form-group">
#Html.LabelFor(model => model.data1)
<div>
#Html.EditorFor(model => model.data1)
#Html.ValidationMessageFor(model => model.data1)
#Html.ValidationMessageFor(model => model.data2)
</div>
</div>
Make sure to leave the #Html.EditorFor helper completely off for the data2 property. Now fill in zero in the form field (you'll only one form field in the view of course now), and post to your action.
ModelState will come back as true in this scenario, even though only one form field is being posted. Not a good result if someone does underpost! So here's the (slightly modified) original model class where underposting issues will occur in the case a form field is left off of your form (note the Required attributes don't make any difference in this situation as both properties are value types):
//You could add the Required attribute or not, doesn't matter at this point.
//The concern here is that the Modelstate will still come back as Valid
//in the case of a form field being left off of your form (or someone underposts).
//So to replicate underposting issues, make sure to comment or delete
//at least one Html.EditorFor helper in the view.
//[Required] Underposting will occur regardless if this is marked required or not,
//so be careful if someone does underpost your form.
public Int32 data1 { get; set; }
//[Required]
public Int32 data2 { get; set; }
Now the solution if you want to solve the underposting issue:
Simply mark both properties as required and make them nullable as mentioned in the articles you provided, like so:
[Required]
public Int32? data1 { get; set; }
[Required]
public Int32? data2 { get; set; }
Now when the view is posted with a missing #Html.EditorFor helper or a missing form field, the ModelState Validation will come back as false, and you're protected from underposting issues.

Client Side Validation fails when moving to viewmodel

This seems to a common question for lots of reasons that do not seem to apply to this situation. I have create page using ASP.NET MVC 2 and I was using a strongly typed view to a class generated from DataEnities framework.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVC_EDI.Models.wysCustomerEndPoint>"" %>
I made validation class that I bound back to the the data class.
[MetadataType(typeof(EndPointValidation))]
public partial class wysCustomerEndPoint
{
}
[Bind()]
public class EndPointValidation
{
[Required(ErrorMessage = "Please enter the end point name")]
public string CustName { get; set; }
And I was able to use client side validation on my create page. I had a requirement to add a dropdown list box on the create page, so I switched my view to use a viewmodel instead of the data class I was using.
public class CreateEditCustomerEndPointsViewModel
{
public wysCustomerEndPoint CustomerEndPoint {get; set;}
public List<SelectListItem> DefaultLocationList { get; set; }
}
and here is the view header using the new viewmodel.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVC_EDI.ViewModles.CreateEditCustomerEndPointsViewModel>" %>
But now when this view gets loaded I am getting an error that my formElement is null when it tries to set a value ? I error out here inteh MicrosofyMvcValidation.js file and the formElement array is null.
formElement['__MVC_FormValidation'] = this
I suspect I need to add some sort of data annotation or attribute to either my view model or something like that. But I am not sure where? And surprisingly it seems to work out just fine in FireFox 5 but bombs in IE9?
Edit: thanks for the reply. Yes I believe I am instantiating the object before adding to the ViewModel and using the Html.Helper objects? Here is the code.
wysCustomerEndPoint ep = new wysCustomerEndPoint();
ep.BuyerID = id;
var viewModel = new CreateEditCustomerEndPointsViewModel()
{
CustomerEndPoint = ep
};
return View(viewModel);
and in the view
<div class="editor-label">
<%: Html.Label("Name") %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.CustomerEndPoint.CustName) %>
<%: Html.ValidationMessageFor(model => model.CustomerEndPoint.CustName) %>
</div>
cheers
bob
You're maybe doing this, but without seeing the relevant bits of code I don't want to assume. So, make sure you are instantiating the wysCustomerEndPoint object and sending to your view from the Controller method. Also that you are using the Html Helpers for the input elements that you are validating on. Eg.
Html.TextboxFor(model => model.wysCustomerEndPoint.CustName)

Button Event in ASP.NET MVC

I have created view page in MVC like
<%using (Html.BeginForm())
{ %>
<%=LabelHelpers.Label("firstname", "FirstName:")%>
<br/>
<%=Html.TextBox("firstname")%>
<br/><br/>
<%=LabelHelpers.Label("lastname", "Lastname:")%>
<br/>
<%=Html.TextBox("lastname")%>
<br/><br/>
<input type="Button" value="Register"/>
<%} %>
Here I want to write Buttonclick Event ...How and Where should i write?
Your input is of type button - these don't do anything without additional client side code.
If you want to handle the 'event' on the server in a similar way that you would have in ASP.NET, you should convert it to a submit button. Assuming your controller is called 'Account' and your action is called 'Register' your current code would look something like this:
public ViewResult Register()
{
return View();
}
You want to start by passing a model to the view:
public ViewResult Register()
{
var registerModel = new RegisterModel();
return View(registerModel);
}
Your current view is using loosely typed inputs. Since you're passing it a model you can use strongly typed views. Your model should look something like this:
public class RegisterMode
{
public string Firstname { get; set; }
public string Surname { get; set; }
}
To use strongly typed views, change your view to look like this:
<%using (Html.BeginForm())
{ %>
<%=Html.LabelFor(x => x.Firstname)%>
<br/>
<%=Html.TextBoxFor(x => x.Firstname)%>
<br/><br/>
<%=Html.LabelFor(x => x.Surname)%>
<br/>
<%=Html.TextBoxFor(x => x.Surname)%>
<br/><br/>
<input type="submit" value="Register"/>
<%} %>
What we've done is told the view to build labels and text boxes for your RegisterModel type. This will allow the model values to be automatically mapped when you POST the form to the controller.
Do accept the post, we need to add a new Action to the controller, with the same name, but accepting a parameter of type RegisterModel:
public ActionResult Register(RegisterModel model)
{
// do something with the model, such as inserting it into the database.
// model.Firstname will contain the value of the firstname textbox
// model.Surname will contain the value of the surnaem textbox
return RedirectToAction("Success");
}
One last thing to do, to be safe, is to add the [HttpGet] and [HttpPost] attributes to your controller actions to control the methods they accept:
[HttpGet]
public ViewResult Register()
and
[HttpPost]
public ActionResult Register(RegisterModel model)
I suggest you read up on MVC at http://www.asp.net/mvc and read the NerdDinner tutorial chapter in Professional MVC (available for free online in PDF format).
joining to the question, want to make it more concrete
i have a form, the form already has a submit button, but i need to bind an additional action to another button.
yes, i do know that MVC does not support events 'cause HTML forms doesn't support them.
so the solution i've came to is to create to hidden inputs inside the form and bind an 'onclick' event (jquery 'live' method) to every... oh, what the hell? here is the code:
html:
<input type="hidden" id="SenderControlID" name="SenderControlID" value="-1" />
<input type="hidden" id="SenderControlValue" name="SenderControlValue" value="-1" />
js:
if ($('#SenderControlID')[0]) {
$('input[type="submit"], input[type="button"], input[type="checkbox"], input[type="radio"]').live('click', function () {
$('#SenderControlID').val($(this).attr('name'));
$('#SenderControlValue').val($(this).val());
});
}
but maybe there is more elegant solution?

Mvc2 validation summary and required metadata

source code...
Thing is, if i specify required metadata using fluent modelmetadata provider like this=>
public class Foo
{
public string Bar { get; set; }
}
public class FooModelMetadataConfiguration : ModelMetadataConfiguration<Foo>
{
public FooModelMetadataConfiguration()
{
Configure(x => x.Bar)
.Required("lapsa") ;
}
}
And write this into my view =>
<% Html.BeginForm(); %>
<%= Html.ValidationSummary() %>
<%= Html.TextBoxFor(x=>x.Bar) %>
<% Html.EndForm(); %>
And add this to home controller =>
[HttpPost]
public ActionResult Index(Foo foo)
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View(foo);
}
It will output this html =>
<div class="validation-summary-errors">
<ul>
<li>lapsa</li>
<li>The Bar field is required.</li>
</ul>
</div>
I can't understand why 2nd error is rendered and how to omit it.
Author of System.Web.Mvc.Extensibility framework replied with =>
I think this is a known issue of asp.net mvc, i could not remember the exact location where I have read it, I suggest you post the issue in asp.net mvc issue tracker over codeplex.
But before i post anything on issue tracker - i would like to understand first what exactly is wrong.
Any help with that?
It's fixed now.

ASP.NET MVC - MasterPageView and RenderPartials - Confusion

I'm a little confused with trying to do bring a list of Categories into a navigation bar on a MasterPageView in the latest release of the ASP.NET MVC framework.
I have 0 experience with Partials so far (this adds to the confusion).
Should I use this variant of the RenderPartial?
HtmlHelper.RenderPartial(string partialViewName, object model)
I wasn't able to find any good examples of this method. By convention there is no model associated with the MasterPageView right? So what is the proper way to push or pull data into a "partial" from the MasterPageView?
Assuming that this method is absolutely going down the wrong path:
<div id="navigation">
<%
CategoryRepository cr = new CategoryRepository();
IList<Category> lst = cr.GetCategories();
Html.RenderPartial("NavBar", lst);
%>
</div>
Do you not want your masterpage to have viewdata? You could solve it by having a base view data class that ALL your other viewdata classes inherit from...
BaseViewData.cs - this is a viewdata class that all other viewdata classes will inherit from
public class BaseViewData
{
public string Title { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
IList<Category> NavCategoryList { get; set; }
}
Now in your Site.Master page simply have
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<BaseViewData>" %>
<title><%=ViewData.Model.Title %></title>
<meta name="keywords" content="<%=ViewData.Model.MetaKeywords %>" />
<meta name="description" content="<%=ViewData.Model.MetaDescription %>" />
<%= Html.RenderPartial("NavBar", ViewData.Model.NavCategoryList) %>
This could significantly impact your application architecture, but its not necessarily a bad thing.
HTHs,
Charles
public ActionResult NavBar()
{
CategoryRepository cr = new CategoryRepository();
IList<Category> lst = cr.GetCategories();
return View(lst);
}
on your partial call
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%# Import Namespace="app.Models" %>
and do all your rendering ui here
<div id="navigation">
<%
Html.RenderPartial("NavBar");
%>
</div>
you can do ActionResult calls in your controllers
I would say that since it's the Master Page you would probably have to store your data that you are passing in ViewData with a string key. If it was a regular view page it would be better to have a strongly typed page, but this is a different case. So you would probably do something this in your controller:
ViewData["MasterPageData"] = FunctionToGetData();
And then on the Master Page something like this:
<%
if (ViewData["MasterPageData"] != null)
{
Html.RenderPartial("ControlName.ascx", ViewData);
}
%>
Then in the control, process like you would on a normal view page:
<% var categories = (CastIfNeeded)ViewData["MasterPageData"]; %>
process as normal...
I haven't had to pass data to a master page yet, but that's how I would think you'd do it. More info here.
EDIT: Changed it around a little to reflect what I'm doing in my current project.
I would use Html.RenderAction() instead and return a partial view from it.

Resources