Donate

Unable To Pass MongoDB's Object ID To Update Controller Action In ASP.NET MVC

When passing a model to the Update action, you may notice that the id field contains series of zeroes instead of the GUID value given the action below.
public ActionResult EditActivity(UserActivity userActivity)
{
     if(userActivity != null)
  {
  userRepository.Update(userActivity);
  }

 return RedirectToAction("Index");
}
I already have set the @Html.HiddenFor() in the page with the value of the ID. After doing some research, I came up with the solution which is to change the @Html.HiddenFor(model => model.Id) element to @Html.Hidden().
@using (Html.BeginForm("EditActivity", "Home", FormMethod.Post))
{
 @Html.AntiForgeryToken()
 @Html.Hidden("id", Model.Id)

 //your html form elements here...
} 
And in the controller action, add another parameter for the id which is of type string.
public ActionResult EditActivity(UserActivity userActivity, string id)
{
     if(userActivity != null)
  {
     userActivity.Id = ObjectId.Parse(id);
  userRepository.Update(userActivity);
  }

 return RedirectToAction("Index");
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input