Html.RenderPartial不会产生值

4

大家好。

我知道这是MVC中非常基础的问题,但是我却无法让@Html.RenderPartial不出错。我正在使用VB.NET和Razor。我在Index视图中使用了这个方法,而Index视图又被_Layout.vbhtml渲染:

@Section MixPage
    @Html.RenderPartial("_MixScreen", ViewData.Model)
End Section

上述表达式不会产生值。
今天早上我找了相当长的一段时间,我正在从以下页面中获取示例:

http://geekswithblogs.net/blachniet/archive/2011/08/03/walkthrough-updating-partial-views-with-unobtrusive-ajax-in-mvc-3.aspx

从控制器内部获取局部视图的HTML

最终,我要做的是从控制器返回更新后的模型到局部视图:

    Function UpdateFormulation(model As FormulationModel) As ActionResult
        model.GetCalculation()
        Return PartialView("_MixScreen", model)
    End Function

这个控制器是从JavaScript表达式中调用的:

function UpdateResults() {
    jQuery.support.cors = true;
    var theUrl = '/Home/UpdateFormulation/';
    var formulation = getFormulation();
    $.ajax({
        type: "POST",
        url: theUrl,
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(formulation),
        success: function (result, textStatus) {
            result = jQuery.parseJSON(result.d);
            if (result.ErrorMessage == null) {
                FillMixScreen(result);
            } else {
                alert(result.ErrorMessage);
            }
        },
        error: function (xhr, result) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
        }
    });
}

如果有更好的方法将更新后的模型返回给视图并仅更新此部分视图,我很愿意听取建议。但是这个问题的前提是:为什么RenderPartial不会产生值?
2个回答

12

Html.RenderPartial 直接写入响应流中,不会返回任何值。因此,您必须将其用于代码块内。

@Section MixPage
    @Code
        @Html.RenderPartial("_MixScreen", ViewData.Model)
    End Code
End Section

你也可以使用不带代码块的 Html.Partial() 来做同样的事情,因为 Partial() 返回一个字符串。

@Section MixPage
    @Html.Partial("_MixScreen", ViewData.Model)
End Section

非常好的回复。这非常清晰,回答了我问题的另一部分。谢谢! - AaronBastian

1

客户的问题在于您的客户端期望的是 html 而不是 Json,记得返回视图,基本上您返回的是编译后的视图,其中包括 html,请将您的结果数据类型更改为 html。

$.ajax({
    type: "POST",
    url: theUrl,
    contentType: "application/json",
    dataType: "html",
    data: JSON.stringify(formulation),
    success: function (result, textStatus) {
        result = jQuery.parseJSON(result.d);
        if (result.ErrorMessage == null) {
            FillMixScreen(result);
        } else {
            alert(result.ErrorMessage);
        }
    },
    error: function (xhr, result) {
        alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
        alert("responseText: " + xhr.responseText);
    }
});

另外,我建议您使用load方法,它是ajax的简短版本,并始终假定预期结果是HTML,并将其附加到所需元素的主体中。

第二,如果您想要从布局中加载部分,请按以下方式执行

 //note's that i'm calling the action no the view
 @Html.Action("UpdateFormulation","yourController", new { model = model}) //<--- this is code in c# don't know how is in vb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接