1

If you pass an anonymous object back to the controller, it populates controller arguments by looking at the anonymous object property names - so how would I pass back properties of related objects to my model so that the default value binder can bind them?

For example:

Model:

public class MyViewModel
{
    public MyItem MyItem { get; set; }
}

public class MyItem
{
    public string Name { get; set; }
}

Controller:

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

In the view, I want to pass the MyItem.Name back, how is this possible? I have tried:

@Html.ActionLinke("Index", "MyController", new { name = "example" })

and

@Html.ActionLinke("Index", "MyController", new { myItem_Name = "example" })

Help please!

4 Answers 4

2

Have you tried:

@Html.ActionLink("Index", "MyController", new { name = @Model.MyItem.Name })

And in the action method:

public ActionResult Index(string name)
{
    return View();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I know I can do it that way but I thought the default model binder could handle inheritance so all I would have to have as a parameter is my view model object.
1

You could use the following overload:

@Html.ActionLink( 
    "link text",                             // linkText
    "Index",                                 // actionName
    "MyController",                          // controllerName
    new RouteValueDictionary {               // routeData
        { "MyItem.Name", "example" } 
    }, 
    null                                     // htmlAttributes
)

Comments

1

I think you may be misunderstanding 'the passing of object from view to controller'. It's not that you're passing object - you're just rendering a link (anchor tag) in the page. The request will actually come from the browser when the user clicks the link. There is no 'server-side object passing' going on.

The link has to contain all the parameters you need on the server side (in controller) as query string parameters.

I think that what you really want to do is either:

  1. render a form and submit it, or

  2. pass only the id of the data you need and in the controller retrieve it (from DB for example)

Comments

0

The answer was to create a custom ModelBinder and ModelBinderProvider.

Comments

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.