是否有可能使用AJAX来访问HTML帮助? [英] Is it possible to use AJAX to access an html helper?

查看:217
本文介绍了是否有可能使用AJAX来访问HTML帮助?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在asp.net MVC3,

In asp.net mvc3,

我使用JavaScript API动态渲染的用户界面。输入部分的一部分将是依赖于用户多少项目要进行输入数据。其结果是,这样的事情不会工作。

I am using a javascript API to dynamically render a user interface. Part of the input section is going to be dependent on how many items the user wants to enter data for. As a result, something like this wont work

@(Html.EditorFor(m => m.P[5].C.Description))

,因为不能在运行期间完成。什么类型的过程中,我会用的AJAX在运行时调用帮手?我想有一个控制器动作只返回这是使用一种称为信息 $。阿贾克斯()?难道是在不同的地方比一个控制器动作?

because that cannot be done during runtime. What type of process would I use to call that helper during runtime with AJAX? Would I have a controller action which only returned that information which was called using $.ajax()? Would it be in a different place than a controller action?

推荐答案

在运行时,你可以执行一个AJAX到一个控制器动作,将呈现一个视图作为字符串,这反过来又可以插入/追加到DOM

At run time you could perform an ajax get to a controller action that will render a view as a string, which in turn could be inserted / appended into the DOM.

创建一个新的动作结果返回JSON按如下:

Create a new action result that returns JSON as per below:

    return new JsonResult
    {
        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
        Data = new { html = this.RenderPartialViewToString("YourPartialView", model) }
    };

请注意,上面使用了以下控制器扩展的:

Note, the above makes use of the following controller extension:

    public static string RenderPartialViewToString(this Controller controller, string viewName = null, object model = null)
    {
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
        }

        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();
        }
    }

有关此扩展方法进一步阅读:http://crafty$c$cblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

所有这一切将保持将执行一个获取传递参数标志着项目的数量来呈现和追加返回的内容到图。也许是这样的:

All that would remain would be to perform a get passing a parameter signifying the number of items to render and append the returned content into your view. Perhaps something like:

    $.getJSON('url', numberofitems, function (data) {
        $('#somecontainer').html(data.html);
    });

这篇关于是否有可能使用AJAX来访问HTML帮助?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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