简体   繁体   中英

How to add code (or markup) dynamically to the view code from controller MVC3

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. Eg 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

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>
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM