Reputation: 718
Bear with me as it might be quite difficult to explain the issue I am seeing, it is frying my brain because it makes no sense (or I am missing a key component to the logic).
I have a view model object A
that I am passing from the controller to a strongly typed view B
which is expecting a model of A
's type. When I wrap the HTML in view B
in a @using (Html.BeginForm(...))
block (I tried with both FormMethod.Post
and FormMethod.Get
just to test), the runtime environment throws an exception when it runs into the following code:
@for (int i = 0; i < Model.DataTable.Columns.Count; i++)
Because the Model
in the code above is null. I stepped through the action that returns view model A
to view B
to make sure that I wasn't passing in a null model, and I can guarantee that I am not. In fact, there are some lines where I use LINQ to generate HTML (e.g., yFor(x => x.Report.Name)) BEFORE the aforementioned
for` loop, and those lines are being processed just fine. When I remove the `` encapsulation block, it works fine.
The kicker is that virtually identical code works in other views with other view models. I am using the same style of for
loop in another view C
that expects a view model D
, and it is all encapsulated in a `` block like I am trying to do with A
and B
.
EDIT: Here is essentially what it looks like. I hope it's enough. I'm afraid I can't give much more.
/* here is a very basic controller action */
[HttpGet]
public ActionResult View()
{
ViewModel vm = new ViewModel();
vm.Name = "view model test";
vm.Table = new DataTable();
return View(vm);
}
/* here is the view */
@model MyMVCProject.Models.ViewModel
@using (Html.BeginForm("View", "Controller", FormMethod.Post))
{
<h2>Test for: </h2>
@Html.DisplayFor(x => x.Name)
<p>Rows</p>
@for (int i = 0; i < Model.Table.Rows.Count; i++)
{
<p>@Model.Table.Rows[i].Name</p>
}
<input type="submit" value="OK"/>
}
Upvotes: 0
Views: 89
Reputation: 718
Ah... this is so embarrassing. I'm pretty sure the compiler was confused between my View
action and the View
type which I am returning in the action. I renamed the action and everything is working as expected.
Upvotes: 1