ASP ViewModel from controller (the Model not model => model.FieldName) became null when postback to controller action

StackOverflow https://stackoverflow.com/questions/23579163

Question

I have an mvc aspx page with strongly typed model, it looked like this

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeliveryService.ViewModels.DeliveryRequestViewModel>" %>

so when I call a create function, the page shows the initialized data from the view model

but when I submit the form (calling the postback create function)

I got a null exception error like on the line:

<%: Html.DropDownListFor(model => model.FromGroup, Model.LocationList) %>

the error pointed to Model.LocationList

I have another field in the aspx page, but it doesn't triggering null exception, the code looks like this

<%: Html.EditorFor(model => model.Address) %>

Please point my error, why is when I use the Model with capital at the first letter I get a null exception error. Thank you very much

I have an extra question:

<%: Html.EditorFor(model => model.DeliveryRequestNumber, new {@readonly = "readonly"}) %>

what is the correct syntax to create a readonly textbox using editorfor? tried this but, the rendered html code is

<input class="text-box single-line valid" id="DeliveryRequestNumber" name="DeliveryRequestNumber" type="text" value="somevaluegeneratedfrommodel">
Was it helpful?

Solution

1 Why do I get a NRE?

I'm guessing, but your reference to 'PostBack' might mean that you come from a WebForms background. In MVC, controller actions must always return the FULL state required to render the view (e.g. in the ViewModel), even after a POST:

[HttpPost]
ActionResult Create(DeliveryRequestViewModel someModel)
{
   //  Do something
   return View("SomeView", someModel); <-- Remember to pass the ViewModel again
}

2 Re : Model vs model

Please point my error, why is when I use the Model with capital at the first letter I get a null exception error. Thank you very much

Model is an instance of the type of the page's model - DeliveryRequestViewModel in this case. (From Inherits="ViewPage<DeliveryRequestViewModel> of the .aspx, or from @model in razor)

Whereas in this case:

<%: Html.EditorFor(model => model.Address) %>

model is a placeholder variable for a lambda expression which projects the Address property off the variable. Placeholder, because it could be anything, e.g.

Html.EditorFor(foo => foo.Address)

3 Re:Readonly Text Box

This here has some ideas

Also, I guess you could just use Html.DisplayFor if you just want to render the value?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top