获取的局部视图的HTML从控制器内 [英] Getting a Partial View's HTML from inside of the controller

查看:254
本文介绍了获取的局部视图的HTML从控制器内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了我的MVC网站通过jQuery,然后填充指定格在HTML拉的简单机制。一切都很好,它看上去很酷。

我的问题是,我现在创建我的控制器内的HTML标记(这是很容易在VB.net做的BTW)我宁愿不混淆的担忧sepparation。

I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.
My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.

是否可以使用自定义'MVC视图用户控件',以适应这种需要?我可以创建一个控件的实例,通过模型中的数据并呈现为HTML?那么这将是渲染和传递回调用浏览器的一个简单的事情。

Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.

推荐答案

您有几种选择。

创建您的控制器视图中的MVC视图用户控制和操作处理。渲染视图的使用

Create a MVC View User Control and action handler in your controller for the view. To render the view use

<% Html.RenderPartial("MyControl") %>

在这种情况下,您的操作处理程序需要将模型数据传递给视图

In this case your action handler will need to pass the model data to the view

public ActionResult MyControl ()
{
    // get modelData

    render View (modelData);
}

您另一种选择是从父页面传递模型数据。在这种情况下,不需要的动作处理程序和模型类型是相同的父

Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent:

<% Html.RenderPartial("MyControl", ViewData.Model) %>

如果您的用户控件有它自己的数据类型,你还可以在页面中构造它

If your user control has it's own data type you can also construct it within the page

在MyControl.ascx.cs:

In MyControl.ascx.cs:

public class MyControlViewData
{
    public string Name { get; set; }
    public string Email { get; set; }
}

public partial class MyControl : System.Web.Mvc.ViewUserControl <MyControlViewData>
{
}

而在你的页面,您可以初始化控件的数据模型:

And in your page you can initialize your control's data model:

<% Html.RenderPartial("MyControl", new MyControlViewData ()
   {
        Name= ViewData.Model.FirstName,
        Email = ViewData.Model.Email,
   });
 %>

这篇关于获取的局部视图的HTML从控制器内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆