Question

I'm dealing with this problem.

I'm using EditorFor for a model which is an abstract class.

@model Contoso.Core.Base.Question

@Html.HiddenFor(model => Model.Id)
@Html.Hidden("ModelType", Model.GetType().AssemblyQualifiedName)

@Html.EditorFor(model => Model, Contoso.Core.QuestionRepositoryManager.GetQuestionView(Model))

As you can above, later invoke a concrete editor for the model and what does MVC is only render the first one (I mean, print hidden input fields "Id and ModelType", but not for the inputs in the concrete EditorFor).

How can I do to print these two EditorFor? I was reading about using PartialView, but I don't like this idea because I don't know how to bind these properties in the POST Method.

UPDATE:

  1. I'm not sure if do I have to modify the prefixHtml to fix this?

    ViewData.TemplateInfo.HtmlFieldPrefix = ...

  2. It renders the second template because if I change to Editor instead of EditorFor

    @Html.Editor("abc", Contoso.Core.QuestionRepositoryManager.GetQuestionView(Model))

Was it helpful?

Solution

I believe the problem here is that the compiler is choosing the wrong overload. If you look at the overloads of EditorFor, you see there are two that take two parameters:

public static MvcHtmlString EditorFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression,
Object additionalViewData
)

and

public static MvcHtmlString EditorFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression,
    string templateName
)

You could try this:

@Html.EditorFor(model => Model, 
     Contoso.Core.QuestionRepositoryManager.GetQuestionView(Model) as string)

or you could do this:

 @Html.EditorFor(model => Model, 
     Contoso.Core.QuestionRepositoryManager.GetQuestionView(Model), null)

There are also two constructors that take 3 arguments, but either of them, the second argument is always the template name, so by passing null it really doesn't matter which is chosen.

The problem may also be that GetQuestionView() returns an object instead of a string, and that is why it's choosing the wrong constructor, making sure the return type of GetQuestionView() is string may also fix it. Although I'm not sure why it works with Editor, since the same problem would exist there as the constructors are pretty analogous.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top