Search code examples
asp.net-mvcsitecoresitecore8sitecore-mvcglass-mapper

Model binding not working properly for Sitecore.Data.ID type while submitting through a Form


I am experiencing a model binding problem, My id is of type Sitecore.Data.ID. After submitting the form, all the other fields gets bonded with correct data, however my Id gets changed to something else.

For example, in the form, the value for hidden field 'id' is 2fb3169c-8b3f-4618-ac78-6170fd0eb297, after submitting to CartController, the value becomes {{68CE2980-7611-422B-96E1-29C4CC0132D5}} or {{82F7914C-34D6-4009-B301-53C1499774A3}} or something else.

I think its random. I am not sure where I going wrong.

I have a Model like this:

 [SitecoreType(AutoMap = true,Cachable = true)]
 public class Book : Item
 {
     public virtual ID Id { get; set; }

     [SitecoreField(IsRequired = true)]
     public virtual string Name { get; set; }

     [SitecoreField(IsRequired = true)]
     public virtual double Price { get; set; }

     [SitecoreField(IsRequired = true)]
     [StringLength(50, MinimumLength = 5)]
     public virtual string Description { get; set; }
 }

This is my view:

    @model Book
          using (Html.BeginRouteForm(Sitecore.Mvc.Configuration.MvcSettings.SitecoreRouteName, FormMethod.Post)

)
        {
            @Html.Sitecore().FormHandler("Cart", "Index")


                @Html.HiddenFor(x => Model.Id)

            <div>
                @Html.DisplayFor(x => book.Name)
                @Html.EditorFor(x => book.Name, new { @class = "bold" })  

            </div>
            <div>
                @Html.DisplayFor(x => book.Price)
                @Html.EditorFor(x => book.Price, new { @class = "bold" })  

            </div>
            <div>
                @Html.DisplayFor(x => book.Description)
                @Html.EditorFor(x => book.Description, new { @class = "bold" })  

            </div>
             <input type="submit" />
            }

This is the cart controller:

 public class CartController : GlassController
 {
      [HttpPost]
      public ActionResult Index(Book book)
      {
          string id = book.Id.ToString();
          if (!string.IsNullOrEmpty(id))
          {
              book = SitecoreContext.GetItem<Book>(new Guid(id), false, true);
              return PartialView("~/Views/Cart/details.cshtml", book);
          }
          return Redirect("http://google.com");
      }
  }        

Solution

  • The Id represents the item Id in the glass mapper. So, instead of using

    public virtual ID Id { get; set; }
    

    change it to this one:

    [SitecoreId] 
    public virtual Guid Id { get; set; }