[RESOLVED]MVC Complex Model Binding

I have two C# POCO class 

public partial class Hotel
public int Id { get; set; }
public string Name { get; set; }
public virtual Hotel_Rate Rate { get; set; }


public partial class Hotel_Rate
public Hotel_Rate()
this.Hotel = new HashSet<Hotel>();

public int Id { get; set; }
public string Rate { get; set; }
public string Description { get; set; }

public virtual ICollection<Hotel> Hotel { get; set; }

I have a viewBag for To Populate dropdown list from Hotel_Rate Class as below

 ViewBag.Hotel_Rate = new SelectList(db.Hotel_Rate, "Id", "Rate");

and in Create View For Hotel Model View Bag Is Used as below 

 @Html.DropDownListFor(m => m.Rate.Id, (SelectList)ViewBag.Hotel_Rate)

and Hotel controller [Create] methode as below

        public ActionResult Create([Bind(Include = "Id,Name,Rate")] Hotel hotel)
            if (ModelState.IsValid)
                return RedirectToAction("Index");

            ViewBag.Hotel_Rate = new SelectList(db.Hotel_Rate, "Id", "Rate", hotel.Id);
            return View(hotel);

but i get the System.Data.Entity.Validation.DbEntityValidationException Error , i entered ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors in watch windows and drilled down to error 

"The Rate field is required."

"The Description field is required."

i change to 

 @Html.DropDownListFor(m => m.Rate.Rate, (SelectList)ViewBag.Hotel_Rate)

and this time The Describtion field is required.

i drilled to Hotel.Rate object in debugging mode , rate property is populated with Hotel_Rate object i drilled down one step more , the id of hotel_rate object is 0 and the rate is 1 (id of rate from  database )

i am really frustrated how difficult  it is to handle simple case in asp.net mvc .

i don’t want to use custom model binder . default asp.net mvc model binder should  be able to handle this .

how can i handle this without complex code , just simple model binding ? 

i dont think viewModel is Good option , because writing viewmodel class just for simple scenario is really funny , 

In my project, I present a dropdown list like below, at same time, you may check if the SelectList object is correctly built.

 public ActionResult Create()
            var categories = from category in db.Categories
                             select category;
            var slist = new List<SelectListItem>();
            foreach (var category in categories)
                slist.Add(new SelectListItem() { Value = category.Description, Text = category.Description, Selected = true });
            ViewData["categories"] = slist;
            return View();

 @Html.DropDownListFor(model => model.CategoryName, (IEnumerable<SelectListItem>)ViewData["categories"])

Leave a Reply