empty
empty

Reputation: 5444

Html.EditFor not finding editor template

Please help! This is driving me insane.

I'm trying to refactor some code because there's a bunch of cut-and-paste in the Models, Views and Controller.

View Model

namespace Foo.Models.Bar
{
[KnownType(typeof(RecruitEditModel))]
public class RecruitEditModel
{
    //...
    public CommonServicesEditModel Services { get; set; }

Services is a property that contains another class within the model where I'm putting the common code.

View in Foo\Views

@model RecruitEditModel
@* ... *@
@using (Html.BeginForm("RecruitEdit", "AppMgmt", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@* ... *@
@*@Html.Partial("TradeEdit", Model.Services)  <<< DOESN'T BIND *@
 @Html.EditorFor(m => m.Services)  @* BINDS *@
<input type="submit" value="Save" />
}

Using a partial on a nested class won't work because the nested class won't bind. (http://lostechies.com/jimmybogard/2011/09/07/building-forms-for-deep-view-model-graphs-in-asp-net-mvc/)

So I have to use an editor template.

Editor Template in Foo\Views\Shared\EditorTemplates\TradeEdit.cshtml

@model Services.CommonServicesEditModel
    <div class="left">
        <h3>Howdy</h3>
        <div class="left theTrade">General Contracting:&nbsp;&nbsp;</div>
        @Html.EditorFor(model => model.TradeGC)
        @Html.ValidationMessageFor(model => model.TradeGC)
    </div>
    @*...*@

The problem I'm running into is that apparently the editor template isn't being found and instead a default editor is getting generated.

I found this out while trying to tweak the CSS. The "Howdy" in the header in the EditorTemplate is not being generated. No matter what I do, short of commenting out the EditFor call there's no change to the displayed fields.

I'm running debugging on local IIS and I've tried restarting the app pool and refreshing the website but no joy.

How do I get changes in the editor template to propagate to the view?

Upvotes: 0

Views: 1019

Answers (2)

empty
empty

Reputation: 5444

The answer was in something obvious but not so obvious. I thought that the editor template would resolve on the model declaration in the editor template. No, it's easier than that.

The editor template must be named {type}.cshtml.

Another possibility is that I could have used UIHint like this:

   [UIHint("TradeEdit")]
   public CommonServicesEditModel Services { get; set; }

but I haven't tested that.

Thanks to Growing With the Web for the answer.

Upvotes: 2

Martin Solev
Martin Solev

Reputation: 154

In the model 'RecruitEditModel' put the nested class with 'virtual' keyword like this:

namespace Foo.Models.Bar
{
[KnownType(typeof(RecruitEditModel))]
public class RecruitEditModel
{
  //...
  public virtual CommonServicesEditModel Services { get; set; }

and if u have database you should update it after this :)

Upvotes: -1

Related Questions