ASP.NET MVC rendering partial view with jQuery ajax

前端 未结 2 576
独厮守ぢ
独厮守ぢ 2020-12-01 13:33

I have a controller action which renders a partial view:

public ActionResult Details(int id)
{
    DetailsViewModel model = 
        ModelBuilder.GetDetailsV         


        
2条回答
  •  天涯浪人
    2020-12-01 14:13

    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 = $("
    "); $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(); });

    UPDATE:

    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);
        }
    }
    

    Then you're guaranteed to always get a valid HTML response and if you don't, then your basic error an error occured will come into play.

提交回复
热议问题