ASP.NET MVC渲染与jQuery阿贾克斯局部视图 [英] ASP.NET MVC rendering partial view with jQuery ajax
问题描述
我有一个控制器操作这使得部分观点:
I have a controller action which renders a partial view:
public ActionResult Details(int id)
{
DetailsViewModel model =
ModelBuilder.GetDetailsViewModel(id, _repository);
return PartialView("Details", model);
}
和我加载了返回的内容为一个充满活力元素,如下所示:
and I'm loading the returned content into a dynamic element as follows:
$container = appendContainer(); // adds a div to the dom with the correct id
$container.load("MyController/Details", function(response, status, xhr) {
if (status != "success") {
$(container).html('an error has occured');
}
});
所以这将创建一个分区,然后再加载内容返回到该分区。
so this creates a div, and then loads the returned content into that div.
我想稍微改变这种使容器的div只有在调用创建 到控制器是成功的。
I want to alter this slightly so that the container div is only created if the call to the controller is succesful.
所以:
- jQuery的调用控制器动作
- 控制器返回PartialView,或NULL,如果未找到ID为
- 如果PartialView被返回,将容器创建和加载与返回的内容。
- 如果控制器没有找到身份证,没有内容被创建并显示一个警告。
我倒是AP preciate任何指针就如何我可以最好达致这。
I'd appreciate any pointers on how I could best acheive this.
推荐答案
所有负荷
确实是从服务器返回的HTML,那么为什么不只是追加到一个临时的DIV和然后获取HTML从它的成功?
All load
does is return HTML from a server, so why not just append to a temporary div and then get the HTML from it on success?
var $dummy = $("<div>");
$dummy.load("MyController/Details", function(response, status, xhr) {
var $container = appendContainer();
if (status != "success") {
$container.html('an error has occured');
}
else
{
$container.html($dummy.html());
}
$dummy.remove();
});
更新:
如果你期待一个例外,那么你应该处理它。如果你基本上允许出现错误只是为了让状态!=成功
那么这是一个严重的code气味。你应该捕获错误并返回不同的PartialView。
If you're expecting an exception then you should handle it. If you're basically allowing the error to occur just to get status != "success"
then that's a serious code smell. You should catch the error and return a different PartialView.
public ActionResult Details(int id)
{
try
{
DetailsViewModel model =
ModelBuilder.GetDetailsViewModel(id, _repository);
return PartialView("Details", model);
}
catch (SomeException ex)
{
return PartialView("Error", ex.Message);
}
}
然后你保证总能获得一个有效的HTML的响应,如果你不这样做,那么你的基本误差发生错误
将开始发挥作用。
这篇关于ASP.NET MVC渲染与jQuery阿贾克斯局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!