我有一个模型的编辑页面.当我将模型发布回我的控制器时,Id属性为0.如何在帖子上维护Id属性?
我正在发布要查看的模型,因此在get请求中设置了Id属性.我的代码如下.
视图:
@model xandra.Models.ProjectModel @using(Html.BeginForm()) { @Html.HiddenFor(m => m.Id) @Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name) <br /> @Html.LabelFor(m => m.Description) @Html.TextAreaFor(m => m.Description) <br /> @Html.LabelFor(m => m.Website) @Html.TextBoxFor(m => m.Website) <br /> @Html.LabelFor(m => m.Active) @Html.CheckBoxFor(m => m.Active) <input type="submit" value="Save" /> }
控制器:
[Authorize] [HttpGet] [InitializeSimpleMembership] public ActionResult EditProject(string id) { using (var entity = new dixraContext()) { var project = entity.Projects.FirstOrDefault(m => m.UrlName == id); return View(project); } } [Authorize] [HttpPost] [InitializeSimpleMembership] public ActionResult EditProject(ProjectModel model) { using (var entity = new dixraContext()) { var project = entity.Projects.FirstOrDefault(m => m.Id == model.Id); project.Name = model.Name; project.Description = model.Description; project.Website = model.Website; project.Tags = model.Tags; project.Active = model.Active; entity.SaveChanges(); return RedirectToAction("GetProject",project.UrlName); } }
而我的模特
public class ProjectModel { [Key] [required] public long Id { get; set; } [required(AllowEmptyStrings=false)] public string Name { get; set; } [required(AllowEmptyStrings=false)] public string Description { get; set; } [required] public DateTime CreatedDate { get; set; } [required] public int Creator { get; set; } public string Website { get; set; } [required] public int CategoryId { get; set; } public virtual List<TagModel> Tags { get; set; } public string UrlName { get; set; } public bool Active { get; set; } }