Question

I have the following model in MVC:

public class IndexViewModel
{
    public SubViewModel SubViewModel { get; set; }
}

In my Index view I am doing the following to display an Editor for SubViewModel:

Index.cshtml

@model IndexViewModel

@Html.EditorFor(m => m.SubViewModel)

In my SubViewModel.cshtml file I tried to do the following:

EditorTemplates/SubViewModel.cshtml

@model SubViewModel

@Html.EditorForModel("SubViewModelForm")

Basically, I want to split apart my Editor into two pieces. The first editor template would create the form, and the inner one would create all of the actual form fields. The problem is that the inner view is never getting rendered.

It's like MVC realizes that I already called EditorFor on that model and is preventing me from doing it again. Is there a way I can get this to work?

EDIT

I thought I typed out what was happening clearly but I guess not.

I want to use two templates to display a single model. In the first template, I want to render the form and the submit button, and a few container divs.

In the second template, I want to render all of the form fields.

Index.cshtml @Html.EditorFor(m => m.SubViewModel) --> render the form and container

SubViewModel.cshtml @Html.EditorForModel("SubViewModelForm") --> render the form fields

The problem is that the second call (@Html.EditorForModel("SubViewModelForm")) doesn't seem to do anything. It never renders any tags at all. It is getting ignored by MVC.

The reason I want to do it this way is because I am going to be posting this form with an ajax call. If everything is okay (model state is valid) then I want to return JSON data to the view. If the model is invalid, I want to return the partial view with just the form fields. This way I don't need to hook up all of my event handlers again. I can just replace the form fields instead of the entire view.

Was it helpful?

Solution

After reading your additional details I believe it would be best to use a container template template.

/* Container.cshtml (container markup and call to editor template) */
<fieldset>                    
    @Html.EditorForModel()
</fieldset>

/* SubViewModel.cshtml editor template */
@model SubViewModel

@Html.DisplayFor(x => x.Property1)
@Html.EditorFor(x => x.Property1)
...

/* Index.cshtml */
@Html.RenderPartial("Container.cshtml", Model.SubViewModel)

OTHER TIPS

I believe this has something to do with TemplateInfo.Visited method. Simply saying, you cannot use EditorFor two times for the same object. That's why mvc is ignoring your second EditorForModel, as editor for SubViewModel has already been rendered (from Index.cshtml).

I do not know if this is the best workaround, but first thing that comes to mind is to render second template as partial view, by calling Html.Partial

@model SubViewModel

@Html.Partial("SubViewModelForm", Model)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top