2

Suppose our class is Dog:

class Dog
{
    public int Age { get; set; };
    public string Name { get; set; };
}

The controller has this Action:

public ActionResult Action(Dog dog)
{
    ...
}

And the View is like this:

using (Html.BeginForm("Action"))
{
    Dog dog = MySession.GetDogFromSession();
    @Html.EditorFor(d => dog.Age);
    @Html.EditorFor(d => dog.Name);
    <input type="submit" value="Action" class="btn btn-default" />
}

The problem is that when the action is called, the Dog instance in the parameters doesn't have the specified Age and Name when the form is posted.

How do you send a Dog instance through this form?

UPDATE:

The view here written is a partial view, so the model is already defined elsewhere.

1
  • Change your parameter to FormCollection and observe the values, I feel the datatype for age might be the problem it might be getting posted as a string Commented May 28, 2014 at 19:23

1 Answer 1

2

@Html.EditorFor uses the model for the View. At the top of your view put this

@model Dog

Then the EditorFor is

@Html.EditorFor(model => model.Age);
Sign up to request clarification or add additional context in comments.

5 Comments

Hum, I should have said that this is a partial view, so the model is already defined in the View that render this partial view.
Should that even matter? I thought MVC operated by scanning the posted data for names that match the properties of the model.
Partial Views can have models too. You pass the model to the partial just like you pass a model to a view.
I changed it, but it still calls the constructor of Dog that takes no parameters instead of the constructor that does have the parameters sent in the form.
You create the instance of Dog when you render the Partial View, not inside the view itself. If you were rendering the controller from a controller, you'd create the instance of dog, set the age and name, and do a PartialView(dog)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.