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

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations