I have an edit page for my model. When i post model back to my controller, Id property is 0. How can i maintain Id property on post?
I'm posting model to view, so Id property is set on get request. My code is below.
View:
@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" />
}
Controller:
[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);
}
}
And my model
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; }
}
I've seen this happen before, it could be a bug. I have been able to work around it by adding the properties I need to be included in the post by not using the specific's view template syntax.
Instead of this:
@Html.HiddenFor(m => m.Id)
Use this:
<input type="hidden" value="@Model.Id" name="Id"/>