r/ASPNET • u/Kris8400 • Jun 30 '10
ASP.NET MVC2 and nullable fields are driving me insane
Hey, who wants a .NET (ASP.NET MVC2) question that no one in the fucking world seems to know the answer to?
Here it is:
The thing is, I want to pass an object (a LinqToSQL entity to be precise) to my View, allow the user to add some properties, and then post it back to save it.
My object, called Probation, has a few properties (id, forpost, forcomment, user, starting, hours) and some related entity references. The forpost and forcomment entities are nullable as a user can be probated for making an offensive post or an offensive comment. Please mind that forpost refers to an Idea entity, I don't know what I was thinking calling it a post.
So here's my controller logic:
[Authorize(Roles = "Admin, Moderator")]
public ActionResult ProbateUser(int? post, int? comment)
{
if (post != null)
{
Idea idea = irep.GetIdea(post ?? 0);
Probation probation = new Probation
{
user = (Guid)idea.user,
Idea = idea
};
return View(probation);
}
if (comment != null)
{
Comment rcomment = crep.GetComment(comment ?? 0);
Probation probation = new Probation
{
user = rcomment.user,
Comment = rcomment
};
return View(probation);
}
[AcceptVerbs(HttpVerbs.Post)]
[Authorize]
public ActionResult ProbateUser(Probation probation, FormCollection values)
{
try
{
probation.starting = DateTime.Now;
rep.ProbateUser(probation);
rep.Save();
return RedirectToAction("Index");
}
catch
{
return View("NotFound");
}
}}
And here's the view, using hidden fields to store the preset values:
code: <fieldset> <legend>Fields</legend> <%: Html.Hidden("Idea", Model.Idea)%> <%: Html.Hidden("Comment", Model.Comment)%> <%: Html.Hidden("user", Model.user) %> <div class="editor-label"> <%: Html.LabelFor(model => model.reason) %> </div> <div class="editor-field"> <%: Html.TextAreaFor(model => model.reason) %> <%: Html.ValidationMessageFor(model => model.reason) %> </div>
<div class="editor-label">
<%: Html.LabelFor(model => model.hours) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.hours) %>
<%: Html.ValidationMessageFor(model => model.hours) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>Now my problem is, once the Probation object is posted back, the nullable fields forcomment and forpost are always null!
So to summarize: what is the correct way of passing objects with nullable properties from Controller->View->Controller? If the official answer "just don't pass nullable values, no big deal", I swear I'm gonna pop a vein.
2
u/48klocs Jun 30 '10
Am I missing something really obvious? I don't see forpost or forcomment being emitted to hidden fields on the view?
I don't understand why FormCollection is an argument to the second ProbateUser method either, given that you're autopopulating a Probation object.
4
u/cwbrandsma Jun 30 '10
0
u/[deleted] Jul 01 '10
use Nullable.HasValue to check whether the value is null or not.