Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

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.

I want to alter this slightly so that the container div is only created if the call to the controller is succesful.

So:

  1. jQuery calls the controller action
  2. controller returns PartialView, or null if Id not found
  3. If PartialView is returned, the container is created and loaded with the returned content.
  4. If the controller doesn't find the Id, no content is created and an alert is displayed.

I'd appreciate any pointers on how I could best acheive this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...