0

How do I pass variables to multiple partial views within a view? My idea is that every partial view will make up a different field in a form, and I plan on using dynamically created DOM objects with each partial view. So I need to pass in 3 parameters. An ID (to uniquely identify each DOM object), and its particular controller and action. How would I go about doing this in a view?

For example, I want to do something along the lines of...

@Html.Partial("_BookField", Model, 1, "book", "updateauthor")

@Html.Partial("_BookField", Model, 2, "book", "updatetitle")

@Html.Partial("_BookField", Model, 3, "book", "updatepublisher")

Is there a way to do this without adding additional attributes in the model?

Edit: After conferring with one of my coworkers, he also brought up a point that I'd like clarification on. He suggested that what I'm doing, which is introducing controller/action logic in the view is breaking the MVC concept. But things like ActionLinks, you have to put in the controller and action in an actionlink for it to be able to do something. Is what I'm trying to do considered breaking the MVC paradigm?

1 Answer 1

2

You use view models of course:

public class SubViewModel
{
    public int Id { get; set; }
    public string Book { get; set; }
    public string Author { get; set; }
}

and then have your main view model different properties of this SubViewModel:

public class MyMainViewModel
{
    public SubViewModel Sub1 { get; set; }
    public SubViewModel Sub2 { get; set; }
    public SubViewModel Sub3 { get; set; }
}

and then simply:

@Html.Partial("_BookField", Model.Sub1)
@Html.Partial("_BookField", Model.Sub2)
@Html.Partial("_BookField", Model.Sub3)

Of course it is the now the controller action responsibility to fill those view models (as always). And if you use editor/display templates your code might be even simpler, just like this:

@Html.DisplayFor(x => x.Sub1)
@Html.DisplayFor(x => x.Sub2)
@Html.DisplayFor(x => x.Sub3)

and because this strangely looks to me like a collection, well, you could use a collection:

public class MyMainViewModel
{
    public SubViewModel[] Subs { get; set; }
}

and then simply:

@Html.DisplayFor(x => x.Subs)
Sign up to request clarification or add additional context in comments.

3 Comments

What happens if you need to send another object in addition to that view model? I mean, is there a way to just send two objects through to a view or a partial view without having to encapsulate them into a class that has both?
@user558594, this shouldn't happen. In this case you simply define an additional property to your view model and it will be sent along.
Ah, I think I got it now. Thanks for the help.

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.