1

In my controller, the view is returned as usual

return new View(myModel);

What I would like is to add some extra code to the view. E.g. under a certain condition, to "wrap" the whole view markup inside a @section. For example, my view is

<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>

And after processing the controller's action, I want the view returned to be

@section MySection{
<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
}

Is it possible?

Thanks

1 Answer 1

4

Its generally a bad idea that your controller injecting markup for a view.

Why don't you enhance your view model to contain the original view model and this condition?

class MyViewModel {
   MyModelType MyModel { get; set; }
   bool Wrap { get; set; }
}

in the view...

@if (!Model.Wrap) {
    <h2>@ViewBag.Title</h2>
    <p>
    @Html.ActionLink("Create New", "Create")
    </p>
}
@section MySection {
   @if (Model.Wrap) {
    <h2>@ViewBag.Title</h2>
    <p>
    @Html.ActionLink("Create New", "Create")
    </p>
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but the issue is I wanted a "shortcut", to not have to alter the view. the reason is I have a lot of views (about 40 entities, each with own index / create / delete / edit / details) which makes 200(!!!) views to change. That's why I wanted some "markup injection". Controller code is generated with a codegen, and I could change it to add code injection part to handle it all for all entities. Any other idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.