Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

asp.net mvc - View not refreshing after AJAX post

I have a view (Index.cshtml) with a grid (Infragistics JQuery grid) with an imagelink. If a user clicks on this link the following jquery function will be called:

function ConfirmSettingEnddateRemarkToYesterday(remarkID) {

    //Some code...

    //Call to action.
$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID },  function (result) {
    //alert('Succes: ' + remarkID);
    //window.location.reload();
    //$('#remarksgrid').html(result);
});

}

Commented out you can see an alert for myself and 2 attempts to refresh the view. The location.reload() works, but is basically too much work for the browser. The .html(result) posts the entire index.cshtml + Layout.cshtml double in the remarksgrid div. So that is not correct.

This is the action it calls (SetEnddateRemarkToYesterday):

       public ActionResult SetEnddateRemarkToYesterday(int remarkID) {

        //Some logic to persist the change to DB.

        return RedirectToAction("Index");
    }

This is the action it redirects to:

[HttpGet]
public ActionResult Index() {
    //Some code to retrieve updated remarks. 
    //Remarks is pseudo for List<Of Remark>
    return View(Remarks);

}

If I don't do window.location.reload after the succesfull AJAX post the view will never reload. I'm new to MVC, but i'm sure there's a better way to do this. I'm not understanding something fundamental here. Perhaps a nudge in the right direction? Thank you in advance.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

As you requesting AJAX call, you should redirect using its response

Modify your controller to return JSONResult with landing url:

public ActionResult SetEnddateRemarkToYesterday(int remarkID) {
    //Some logic to persist the change to DB.
    var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Controller");
        return Json(new { Url = redirectUrl });
}

JS Call:

$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID },  function (result) {
    window.location.href = result.Url
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...