我有一个模型的编辑页面。当我将模型发送回我的控制器时,Id属性为0。如何在提交后保持Id属性?
我正在将模型发布到视图中,因此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; }
}
public int Id { get; set; }
吗? - Win