我几年来一直在阅读stackoverflow,但这是我第一次真的需要发布一个问题,因为我似乎无法在任何地方找到合适的答案。如何将ASP.NET视图的可空属性传递给Controller?
事情是,我想要传递一个对象(一个LinqToSQL实体是精确的)到我的视图,允许用户添加一些属性,然后将其发回以保存它。
我的对象叫做缓刑,有几个属性(id,forpost,forcomment,user,starting,hours)和一些相关的实体引用。前锋和forcomment实体是可空的,因为用户可能会因为发表攻击性言论或冒犯性评论而被指控。请注意,前锋指的是一个理念实体,我不知道我在想什么叫它。
因此,这里是我的控制器逻辑:
[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);
}
return View("NotFound");
}
[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");
}
}
}
而这里的景色,使用隐藏字段存储的预设值:
<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>
现在我的问题是,一旦缓刑对象调回,可空字段forcomment和forpost始终为空!
所以总结一下:从Controller-> View-> Controller传递具有可为空属性的对象的正确方法是什么?请好吗?
但这正是我现在正在做的事?或者我在这里错过了什么? 问题是,使用这种方法,所有*可空*字段,无论值,都设置为* null。我可以有正常的属性没有问题。 – Kris9000 2010-06-30 22:01:41