ASP.NET MVC渲染与jQuery阿贾克斯局部视图 [英] ASP.NET MVC rendering partial view with jQuery ajax

查看:113
本文介绍了ASP.NET MVC渲染与jQuery阿贾克斯局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器操作这使得部分观点:

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.

所以:

  1. jQuery的调用控制器动作
  2. 控制器返回PartialView,或NULL,如果未找到ID为
  3. 如果PartialView被返回,将容器创建和加载与返回的内容。
  4. 如果控制器没有找到身份证,没有内容被创建并显示一个警告。

我倒是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屋!

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