drunkcamel
drunkcamel

Reputation: 915

Using HtmlHelper for inner Model properties

I have such a Model structure for one of my Asp.net MVC views:

public class MyModel{
   public AnotherModel1 Prop1 {get;set;}
   public AnotherModel2 Prop2 {get;set;}
}
public class AnotherModel1{
   public InnerModel InnerProp1 {get;set;}
   public InnerModel InnerProp2 {get;set;}
   public InnerModel InnerProp3 {get;set;}
}
public class AnotherModel2{
   public InnerModel InnerProp1 {get;set;}
   public InnerModel InnerProp2 {get;set;}
}
public class InnerModel {
   public string Input {get;set;}
}

It means, MyModel is general model to pass to View. Some other models AnotherModel1, AnotherModel2 whose contain InnerModel as properties.

I want to create a helper function that will know how to render InnerModel. Then in my page View I want to have an ability to write something like @RenderInnerModel(m => m.Prop1.InnerProp1)

The problem is, I have no idea how to pass htmlhelper into my function to have ability to use @Html.TextBoxFor(m => m.Input) inside my helper.

While the problem could be solved by using partial views per InnerModel, I want to have parameterized helper function and don't want to mess up with complex models for partials e.g. using Tuple etc.


EDIT

While EditorFor seems to be almost what I want, I still want to understand is it possible to have something like

var modelHelper = new HtmlHelper<InnerModel>(ViewContext, this);

but in context of MyModel? Thanks!

Upvotes: 0

Views: 284

Answers (1)

Lucas L Roselli
Lucas L Roselli

Reputation: 2830

Your controller:

  public class AnotherModel
  {
     public InnerModel InnerProp1 { get; set; }
     public InnerModel InnerProp2 { get; set; }
  }
  public class InnerModel
  {
     public string Input { get; set; }
  }

  public class EditorExampleController : Controller
  {
     //
     // GET: /EditorExample/

     public ActionResult Index()
     {
        AnotherModel model = new AnotherModel();
        model.InnerProp1 = new InnerModel { Input = "test 1" };
        model.InnerProp2 = new InnerModel { Input = "test 2" };
        return View(model);
     }
  }

your view:

  @model MVCApp.Controllers.AnotherModel
  <h2>Editor template</h2>
  @Html.EditorFor(_ => _.InnerProp1)
  @Html.EditorFor(_ => _.InnerProp2)

on "shared" folder in "Views" create a new folder call "EditorTemplates", then add a partial view "InnerModel.cshtml" :

  @model MVCApp.Controllers.InnerModel

  @if (Model.Input == "test 2")
  {
     <h4>@Model.Input</h4>
  }
  else
  {
     <h2>@Model.Input</h2>
  }

This is a simple implementation, if you want I can post a Custom HtmlHelper

Upvotes: 2

Related Questions