ASP.NET MVC null ViewResult
Posted
by David Neale
on Stack Overflow
See other posts from Stack Overflow
or by David Neale
Published on 2010-05-11T08:48:33Z
Indexed on
2010/05/11
8:54 UTC
Read the original article
Hit count: 344
How should one deal with an MVC controller returning a null ViewResult?
As an example I am creating a simple edit view:
public ActionResult Edit(int id)
{
var person = (from p in context.SWLiftShare_Persons
where p.id == id
select p).SingleOrDefault();
if (person != null)
{
return View(person);
}
else return View();
}
I guess in reality there's no point in checking for a null result in the controller because the view picks out properties from the model:
<h2>Edit - <%= Html.Encode(Model.Name) %></h2>
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="id">id:
<%= Html.Encode(Model.id) %></label>
</p>
<p>
<label for="CollarNumber">CollarNumber:</label>
<%= Html.TextBox("CollarNumber", Model.CollarNumber)%>
<%= Html.ValidationMessage("CollarNumber", "*") %>
</p>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name", Model.Name)%>
<%= Html.ValidationMessage("Name", "*") %>
</p>
<p>
<label for="EmailAddress">EmailAddress:</label>
<%= Html.TextBox("EmailAddress", Model.EmailAddress, new { style = "width:300px" })%>
<%= Html.ValidationMessage("EmailAddress", "*") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
I could just wrap everything in a <% if(Model != null) { //render edit markup...
etc. but that seems rather unelegant. Is there a better way to deal with this?
© Stack Overflow or respective owner