【发布时间】:2010-07-04 01:44:26
【问题描述】:
我已经阅读 stackoverflow 几年了,但这是我第一次真正需要发布问题,因为我似乎无法在任何地方找到合适的答案。
问题是,我想将一个对象(准确地说是一个 LinqToSQL 实体)传递给我的视图,允许用户添加一些属性,然后将其发回保存。
我的对象叫做 Probation,有一些属性(id、forpost、forcomment、user、starting、hours)和一些相关的实体引用。 forpost 和 forcomment 实体可以为空,因为用户可能会因发表冒犯性帖子或冒犯性评论而受到认证。请注意,forpost 指的是一个 Idea 实体,我不知道我在想什么。
这是我的控制器逻辑:
[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 传递具有可为空属性的对象的正确方法是什么?漂亮吗?
【问题讨论】:
标签: asp.net-mvc-2