Hadas
Hadas

Reputation: 10384

view return empty model asp.net mvc3

I try to initialize the DataView.Model in a partial view. The Page works fine but when I return to the controller the model is empty.

some help(solution or an explanation why it is not right). thanks!!

code:

In my Partial View:

 ViewData.Model = new DiamondPrint();
 ViewData.Model.Diamond = m_db.DiamondInfoes.Where(di => di.Id == id).SingleOrDefault();

In my Controller:

public ActionResult Preview(DiamondPrint d)//the properties in d = null
{
   return View(d);
}

Upvotes: 0

Views: 1952

Answers (2)

Dangerous
Dangerous

Reputation: 4909

Looking at the code you have included it seems that you are initialising the ViewData.Model in the partial view but in the controller action you are expecting the default model binder to recreate your model. For the model binder to recreate your model you will need to have created a strongly typed view.

For example:

Controller:

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(IndexModel model)
{
    return View();
}

Model:

public class IndexModel
{
    public string MyValue { get; set; }
}

View:

Note the @model definition at the top (ignore namespace)

@model MvcApplication14.Models.IndexModel

@using (Html.BeginForm())
{
    @Html.Partial("_IndexPartial", Model)

    <input type="submit" value="click"/>
}

Partial View:

@model MvcApplication14.Models.IndexModel

@Html.EditorFor(m => m.MyValue)

Upvotes: 1

Ryand.Johnson
Ryand.Johnson

Reputation: 1906

Here is a great article on Model Binding. Model Binding Make sure you are setting the name property in your html input fields.

Upvotes: 1

Related Questions