views:

1149

answers:

5

Suppose I have ViewModel like

public class AnotherViewModel
{
   public string Name { get; set; }
}
public class MyViewModel
{
   public string Name { get; set; }
   public AnotherViewModel Child { get; set; }
   public AnotherViewModel Child2 { get; set; }
}

In the view I can render a partial with

<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>

In the partial I'll do

<%= Html.TextBox("Name", Model.Name) %>
or
<%= Html.TextBoxFor(x => x.Name) %>

However, the problem is that both will render name="Name" while I need to have name="Child.Name" in order for model binder to work properly. Or, name="Child2.Name" when I render the second property using the same partial view.

How do I make my partial view automatically recognize the required prefix? I can pass it as a parameter but this is too inconvenient. This is even worse when I want for example to render it recursively. Is there a way to render partial views with a prefix, or, even better, with automatic reconition of the calling lambda expression so that

<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>

will automatically add correct "Child." prefix to the generated name/id strings?

I can accept any solution, including 3-rd party view engines and libraries - I actually use Spark View Engine (I "solve" the problem using its macros) and MvcContrib, but did not find a solution there. XForms, InputBuilder, MVC v2 - any tool/insight that provide this functionality will be great.

Currently I think about coding this myself but it seems like a waste of time, I can't believe this trivial stuff is not implemented already.

A lot of manual solutions may exists, and all of them are welcome. For example, I can force my partials to be based off IPartialViewModel<T> { public string Prefix; T Model; }. But I'd rather prefer some existing/approved solution.

UPDATE: there's a similar question with no answer here.

A: 

Like you, I add Prefix property (a string) to my ViewModels which I append before my model bound input names. (YAGNI preventing the below)

A more elegant solution might be a base view model that has this property and some HtmlHelpers that check if the view model derives from this base and if so append the prefix to the input name.

Hope that helps,

Dan

Daniel Elliott
Hmm, too bad. I can imagine many elegant solutions, with custom HtmlHelpers checking properties, attributes, custom render, etc... But for example if I use MvcContrib FluentHtml, do I rewrite all of them to support my hacks? It's strange that nobody talks about it, as if everybody just uses flat single-level ViewModels...
queen3
Indeed, after using the framework for any length of time and striving for nice clean view code, I think the tiered ViewModel is inevitable. The Basket ViewModel within the Order ViewModel for example.
Daniel Elliott
A: 

How about just before you call RenderPartial you do

<% ViewData["Prefix"] = "Child."; %>
<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>

Then in your partial you have

<%= Html.TextBox(ViewData["Prefix"] + "Name", Model.Name) %>
Anthony Johnston
This is basically the same as passing it manually (it's type safe to derive all view models from IViewModel with "IViewModel SetPrefix(string)" instead), and is very ugly, unless I rewrite all the Html helpers and RenderPartial so that they automatically manage this. The problem is not how to do it, I solved this already; the problem is, can it be done automatically.
queen3
as there is no common place you can put code that will affect all html helpers you would not be able to do this automatically. see other answer...
Anthony Johnston
+4  A: 

Using MVC2 you can achieve this.

Here is the strongly typed view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcLearner.Models.Person>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Create</h2>

    <% using (Html.BeginForm()) { %>
        <%= Html.LabelFor(person => person.Name) %><br />
        <%= Html.EditorFor(person => person.Name) %><br />
        <%= Html.LabelFor(person => person.Age) %><br />
        <%= Html.EditorFor(person => person.Age) %><br />
        <% foreach (String FavoriteFoods in Model.FavoriteFoods) { %>
            <%= Html.LabelFor(food => FavoriteFoods) %><br />
            <%= Html.EditorFor(food => FavoriteFoods)%><br />
        <% } %>
        <%= Html.EditorFor(person => person.Birthday, "TwoPart") %>
        <input type="submit" value="Submit" />
    <% } %>

</asp:Content>

Here is the strongly typed view for the child class (which must be stored in a subfolder of the view directory called EditorTemplates):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcLearner.Models.TwoPart>" %>

<%= Html.LabelFor(birthday => birthday.Day) %><br />
<%= Html.EditorFor(birthday => birthday.Day) %><br />

<%= Html.LabelFor(birthday => birthday.Month) %><br />
<%= Html.EditorFor(birthday => birthday.Month) %><br />

Here is the controller:

public class PersonController : Controller
{
    //
    // GET: /Person/
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Index()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Create()
    {
        Person person = new Person();
        person.FavoriteFoods.Add("Sushi");
        return View(person);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Person person)
    {
        return View(person);
    }
}

Here are the custom classes:

public class Person
{
    public String Name { get; set; }
    public Int32 Age { get; set; }
    public List<String> FavoriteFoods { get; set; }
    public TwoPart Birthday { get; set; }

    public Person()
    {
        this.FavoriteFoods = new List<String>();
        this.Birthday = new TwoPart();
    }
}

public class TwoPart
{
    public Int32 Day { get; set; }
    public Int32 Month { get; set; }
}

And the output source:

<form action="/Person/Create" method="post"><label for="Name">Name</label><br /> 
    <input class="text-box single-line" id="Name" name="Name" type="text" value="" /><br /> 
    <label for="Age">Age</label><br /> 
    <input class="text-box single-line" id="Age" name="Age" type="text" value="0" /><br /> 
    <label for="FavoriteFoods">FavoriteFoods</label><br /> 
    <input class="text-box single-line" id="FavoriteFoods" name="FavoriteFoods" type="text" value="Sushi" /><br /> 
    <label for="Birthday_Day">Day</label><br /> 
    <input class="text-box single-line" id="Birthday_Day" name="Birthday.Day" type="text" value="0" /><br /> 

    <label for="Birthday_Month">Month</label><br /> 
    <input class="text-box single-line" id="Birthday_Month" name="Birthday.Month" type="text" value="0" /><br /> 
    <input type="submit" value="Submit" /> 
</form>

Now this is complete. Set a breakpoint in the Create Post controller action to verify. Don't use this with lists however because it wont work. See my question on using EditorTemplates with IEnumerable for more on that.

NickLarsen
Yes, it looks like it. The problems are that lists do not work (while nested view models are usually in lists) and that it's v2... which I'm not quite ready to use in production. But still good to know it will be something that I need... when it comes (so +1).
queen3
I also came across this the other day, http://www.matthidinger.com/archive/2009/08/15/creating-a-html.displayformany-helper-for-mvc-2.aspx, you might want to see if you can figure out how to extend it for editors (though still in MVC2). I spent a few minutes on it, but kept running into problems because I am not up to par with expressions yet. Maybe you can do better than I did.
NickLarsen
A useful link, thanks. Not that I think it's possible to make EditorFor work here, because it won't generate [0] indexes I suppose (I'd bet it doesn't support it at all yet). One solution would be to render EditorFor() output to string and manually tweak the output (append required prefixes). A dirty hack, though. Hm! I may do extension method for Html.Helper().UsePrefix() which will just replace name="x" with name="prefix.x"... in MVC v1. Still a bit of work but not that much. And Html.WithPrefix("prefix").RenderPartial() that works in pair.
queen3
A: 

I came across this issue also and after much pain i found it was easier to redesign my interfaces such that i didn't need to post back nested model objects. This forced me to change my interface workflows: sure i now require the user to do in two steps what i dreamed of doing on one, but the usability and code maintainability of the new approach is of greater value to me now.

Hope this helps some.

cottsak
+1  A: 

You could add a helper for the RenderPartial which takes the prefix and pops it in the ViewData.

    public static void RenderPartial(this HtmlHelper helper,string partialViewName, object model, string prefix)
    {
        helper.ViewData["__prefix"] = prefix;
        helper.RenderPartial(partialViewName, model);
    }

Then a further helper which concatenates the ViewData value

    public static void GetName(this HtmlHelper helper, string name)
    {
        return string.Concat(helper.ViewData["__prefix"], name);
    }

and so in the view ...

<% Html.RenderPartial("AnotherViewModelControl", Model.Child, "Child.") %>

in the partial ...

<%= Html.TextBox(Html.GetName("Name"), Model.Name) %>
Anthony Johnston
Yes, that's what I described in a comment to http://stackoverflow.com/questions/1488890/asp-net-mvc-partial-views-input-name-prefixes/1489017#1489017. An even better solution would be RenderPartial which takes lambda, too, which is easy to implement. Still, thanks for the code, I guess that's the most painless and timeless approach.
queen3