ASP.NET MVC rendering partial view with jQuery ajax

前端 未结 2 555
独厮守ぢ
独厮守ぢ 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:12

    in your case i would use $.ajax instead of .load() gives you more control over the flow + feels more clean

    $.ajax({
    url: "MyController/Details",
       type: "GET",
       success: function (response, status, xhr)
       {
          var jqContainer = appendContainer();
          jqContainer.html(response);
       },
       error:function(XMLHttpRequest, textStatus, errorThrown)
       {
         //show the error somewhere - but this is a bad solution
       }
    });
    

    concerning the error state - i also hate relying on exceptions - ugly and inefficient, you have several ways to handle this:

    1. return only JSON from your views and bind the returned data using some sort of templating solution, this way you can return an error object with a specific error message and handle all errors the same way(think this is the best solution).
    2. return a 204 success status code -no response which is like returning null from your action - then check the status code and pop up the error message.
    3. return a 278 success status code(not a real status code but is counts for success and lets you also send data) - here you send a json object with the error message which tou can parse and sow a nice error message (saw this 278 solution here in SO sometime ago).
    4. return a different view for the error - but then you have to insert it to the container or a dummy container to check if there is an error if you want to take more actions.

    in my code i use $(document).ajaxSend(..) to globally check all Ajax responses for 278 code and show the error messages if there is any, or call the original hooked success function.

    To return the error from the action i use the following result

        public class AjaxErrorWithDetailsResult : JsonResult
        {
        public object ErrorResult { get; set; }
    
        public AjaxErrorWithDetailsResult(object errorResult)
        {
            this.ErrorResult = errorResult;
        }
    
    
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            this.Data = ErrorResult;
            context.HttpContext.Response.StatusCode = 278;
            base.ExecuteResult(context);
        }
    }
    

    where ErrorResult can be an anonymous object or an object that implement an interface with a property of ErrorMessage so you will know what to look for at the JS

    0 讨论(0)
  • 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 = $("<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();
    });
    

    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.

    0 讨论(0)
提交回复
热议问题