我真的不推荐这种方法 - 如果您想确保调用成功,请使用协议中和jQuery库中内置的HTTPHeader。如果你看看$.ajax
的API文档,你会发现你可以对不同的HTTP状态代码有不同的反应 - 例如,成功和错误回调。 用这种方法,你的代码将看起来像
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $(this).serialize(),
dataType: 'HTML',
success: function(data, textStatus, XMLHttpRequest) {
alert(textStatus);
$('#test').html(data);
},
error: function(XmlHttpRequest, textStatus, errorThrown) {
// Do whatever error handling you want here.
// If you don't want any, the error parameter
//(and all others) are optional
}
}
而且操作方法简单地返回PartialView
:
public ActionResult ThisOrThat()
{
return PartialView("ThisOrThat");
}
但是,是的,这是可以做到的方式太。您的方法存在的问题是您要返回PartialView
本身,而不是输出HTML。如果你把它改成这样您的代码将工作:
public ActionResult HelpSO()
{
// Get the IView of the PartialView object.
var view = PartialView("ThisOrThat").View;
// Initialize a StringWriter for rendering the output.
var writer = new StringWriter();
// Do the actual rendering.
view.Render(ControllerContext.ParentActionViewContext, writer);
// The output is now rendered to the StringWriter, and we can access it
// as a normal string object via writer.ToString().
// Note that I'm using the method Json(), rather than new JsonResult().
// I'm not sure it matters (they should do the same thing) but it's the
// recommended way to return Json.
return Json(new { success = true, Data = writer.ToString() });
}
感谢托马斯 - 我很欣赏的指针再度最佳实践,但我不是在看200或500错误。这更适合验证我返回成功的位置,然后返回相关的局部视图。有成功和失败的观点,但是我仍然需要在返回结果后在页面的其他地方做一些处理。我尽可能简单地举例说明技术答案,而不是设计方案。再次感谢你的回复! – Chev 2010-04-11 06:48:20
托马斯 - 使用mvc 1.0我没有访问ControllerContext.ParentActionViewContext属性? – Chev 2010-04-11 10:57:40
嗯......我所展示的代码显然来自于.NET 4的MVC 2,因为这正是我正在使用的。我将在MVC 1中查看一些方法 - 但我的搜索算法将是“ah,intellisense - 嗯,这是什么?”,所以你可以尽可能地发现它:P – 2010-04-11 11:45:36