Search code examples
asp.net-mvcasp.net-mvc-3razorhtml-helper

asp.net MVC 3, Html.EditorFor in different Model


I have 2 class in Model

public class User
{
    public int UserID { get; set; }
    public string UserName { get; set; }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

I have a view that use both class and I need use html.TextBoxFor. I can create BigModel:

public class BigModel
{
    public User user;
    public Product product;
}

so in View:

@model BigModel
@Html.TextBoxFor(m=> m.user.UserName)
@Html.TextBoxFor(m=> m.product.ProductName)    

Or i can use different partial view and reander them. But they are not my favorite solution.

Isn't there another way? such as:

<p>    
    User Name:
    @Html.TextBoxFor<User>(u=> u.UserName)
</p>
<p>    
    Product Name:
    @Html.TextBoxFor<Product>(p=> p.ProductName)
</p>

Solution

  • Look at TextBoxFor method signature:

    public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression
    )
    

    It's impossible. to write:

    @Html.TextBoxFor<Product>(p=> p.ProductName)
    

    So you are "stuck" with this:

    @Html.TextBoxFor(m=> m.product.ProductName)
    

    (I don't know why you prefer the first version, it's even one char longer... =) )