开发者

ASP.NET MVC3 Import view content programatically on an extension method

开发者 https://www.devze.com 2023-02-19 23:05 出处:网络
I\'m building a state machine which display different action controls (partial views) on the page according to some dynamic value.

I'm building a state machine which display different action controls (partial views) on the page according to some dynamic value.

I started writing HtmlHelper Extension methods to ouput the proper html for each state. Something like:

@if(Model.state == "NEW") {
Html.RenderActionEdit()
Html.RenderActionDelete()
}

And to do this I was doing simple methods in the form:

return MvcHtmlString.Create("<form><input>开发者_开发问答;..... </form>");

But this is rather cumbersome for large bits of html. So, the question is, would it be possible to write this Html on separate views (cshtml files) and then somehow load them and pass the result to MvcHtmlString? Like

return MvcHtmlString.Create(View.Load("EditAction.csthml"));

I couldn't find a way to load an existing view and then just "include" it on the partial method's output.

Many thanks for any help!


There are a couple of ways to do this:

  1. @Html.RenderPartial("thepartial.cshtml", model); will pass model to the partial view, and render it. There are a couple of other versions too.

  2. @Html.Action("action", "controller", id) (see msdn) will pass id to the specified action method, and render the view it outputs. This is very convenient if you don't have the model object needed for the partial available in your main view.

In an extension method on HtmlHelper, you could use it like this:

public HtmlString YourContent(this HtmlHelper helper)
{
    return helper.Action("action", "controller", new { id = 1 });
}

which in your view would be used by calling @Html.YourContent().

0

精彩评论

暂无评论...
验证码 换一张
取 消