我有两页:
- 创建使用数据注释验证的页面。
- 编辑页面。
两个页面使用不同的模型。我必须为编辑页面使用特定模型才能显示所选行的值。我如何能:
- 让编辑控制器使用相同的验证,或者
- 如果我使用与创建页面相同的模型,获取编辑页面以显示当前行的值?
例如:
我的创建页面:
@model Test.Models.NewPerson
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "Failed. Please fix the errors.")
<div class="editor-label">
@Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.FirstName)
@Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.LastName)
@Html.ValidationMessageFor(m => m.LastName)
</div>
<input type="submit" value="Submit" />
}
我的模型:
public class NewPerson
{
[Required(ErrorMessage = "*")]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "Last name")]
public string LastName { get; set; }
}
然后是我的编辑页面:
@model Test.Person
using (Html.BeginForm())
{
@Html.ValidationSummary(true, "Please fix the errors below.")
<div class="editor-label">
@Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.FirstName)
@Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.LastName)
@Html.ValidationMessageFor(m => m.LastName)
</div>
<input type="submit" value="Update" />
}
编辑
在我的控制器中,编辑操作,我有:
var context = new MyContext();
var person = context.Person.Single(m => m.ID == id);
if (Request.IsAjaxRequest())
{
return PartialView("Edit", person);
}
return View(person);
当我在该函数中放置断点时,我看到了 var person 的结果。但是,它在视图中不返回任何内容。为什么不?
编辑
这是我的操作代码:
[HttpPost]
public ActionResult Create(NewPerson model)
{
if (ModelState.IsValid)
{
string UID = Membership.GetUser().ProviderUserKey.ToString();
System.Guid myUID = System.Guid.Parse(UID);
using (var context = new MyContext())
{
Person newPerson = new Person();
newPerson.UserId = myUID;
newPerson.FirstName = model.FirstName;
newPerson.LastName = model.LastName;
context.Person.AddObject(newPerson);
context.SaveChanges();
}
}
和编辑动作:
[HttpGet]
public ActionResult Edit(int id)
{
var context = new MyContext();
//recently edited: accidentally had "camper" instead of "person"
var person = context.Person.Single(m => m.ID == id);
if (Request.IsAjaxRequest())
{
return PartialView("Edit", person);
}
return View(person);
}
我的观点:
@foreach (var person in Model)
{
@Html.DisplayFor(modelItem => person.LastName), @Html.DisplayFor(modelItem => person.FirstName)
@Html.ActionLink("Edit", "Edit", new { id = person.ID }, new { @class = "openDialog",
data_dialog_id = "emailDialog", data_dialog_title = "Edit Person" })
}