控制器:
public ActionResult Edit(int id)
{
SetViewData();
var rule = _db.AlertRules.Find(id);
ViewData["rule"] = rule.Feed.Name + " - "
+ rule.Template.Name;
return View(rule);
}
//
// POST: /AlertRule/Edit/5
[HttpPost]
public ActionResult Edit(AlertRule alertrule)
{
SetViewData();
alertrule.UpdateDateTime = DateTime.Now;
if (ModelState.IsValid)
{
_db.Entry(alertrule).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
TempData["error"] = "Cant update rule({0})"
+ alertrule.Id;
}
return View(alertrule);
}
private void SetViewData()
{
var feeds = new SelectList(_db.Feeds.OrderBy(f => f.Name), "Id", "Name");
var templates =
new SelectList(_db.AlertRuleTemplates.OrderBy(f => f.Name), "Id", "Name");
ViewData["templates"] = templates;
ViewData["feeds"] = feeds;
}
看法:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Edit</legend>
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.FeedId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.FeedId, (SelectList)ViewData["feeds"])
@Html.ValidationMessageFor(model => model.FeedId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TemplateId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.TemplateId,
(SelectList)ViewData["templates"])
@Html.ValidationMessageFor(model => model.TemplateId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Enable)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Enable)
@Html.ValidationMessageFor(model => model.Enable)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Alertrule)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Alertrule)
@Html.ValidationMessageFor(model => model.Alertrule)
</div>
<div class="editor-label" style="display: none">
@Html.LabelFor(model => model.UpdateDateTime)
</div>
<div class="editor-field" style="display: none">
@Html.EditorFor(model => model.UpdateDateTime)
@Html.ValidationMessageFor(model => model.UpdateDateTime)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
表格数据:
Id:33
FeedId:1
TemplateId:1
Enable:false
Alertrule:00000
UpdateDateTime:12/10/2012 3:02:15 PM