【发布时间】:2019-02-11 21:02:09
【问题描述】:
我正在尝试使用 AJAX 调用我的控制器并返回一个带有模型作为字符串的部分视图,以便我可以将它注入到我的 HTML 中。我之前在 MVC5 中使用控制器接口完成了此操作,但我似乎无法找到有关如何在 Asp.Net Core 2.2 中为局部视图执行此操作的任何内容。我找到了如何将视图呈现为字符串的示例,但我无法修改它们以适用于局部视图。
控制器动作:
public JsonResult GetUpsertPartialView(MessageBoard messageBoard)
{
Dictionary<string, string> result = new Dictionary<string, string>();
string errorState = "0";
string errorMessage = "";
try
{
result["view"] = ""; // My call to render the Partial View would go here.
}
catch (Exception)
{
errorState = "1";
errorMessage = "An error was encountered while constructing the View.";
}
result["errorState"] = errorState;
result["errorMessage"] = errorMessage;
return Json(result);
}
AJAX 调用:
$.ajax({
type: "GET",
url: "../Home/GetUpsertPartialView/",
data: messageBoardData,
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log(data);
$("#messageBoardModalBody").val(data.view);
$("#messageBoardModal").modal("show");
}
});
我已经确认我的 Controller 被击中,参数被正确传递,并且我从 Action 接收到正确的数据返回给我的 AJAX 调用。我唯一缺少的是将部分视图直接呈现为字符串的能力。
如果在 Asp.net Core 中有其他方法可以做到这一点,我愿意接受其他选择。
注意:我这样做只是为了学习 Asp.Net Core。如果需要更多信息,请告诉我。
【问题讨论】:
标签: c# asp.net asp.net-core asp.net-core-mvc