简体   繁体   中英

How to move between MVC controllers using knockout.js?

I have an issue with moving from one MVC controller to another. I am new to MVC/Knockout combination and trying to find a best way.

I have a HomeController that does some login processes. The Login view, of the controller, contains knockout script that posts data it. After a certain select is chosen this code is executed by a button press with data-bind="clicked: SubmitLocation"

    self.SubmitLocation = function () {
        var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));
        alert(jsonData);
        $.ajax({
            ur: '@Url.Action("Login", "Home")',
            type: 'post',
            data: jsonData,
            contentType: 'application/json',
            success: function () { }
        });

This brings it to the code inside MVC controller :

    [HttpPost]
    public ActionResult ....{
            return RedirectToAction("Products", "Product");
     ...}

Debugging through the code, I see that it makes it over to the Product controller and even to the Products view, without exceptions. However the page on the browser itself remains on the original HomeController/Login view. Where am I going wrong?

I have also tried returning a different view from the same HOmeController instead of RedirectToAction, and it is still the same.

You can't return RedirectToAction() or return View() to an ajax call. Upon successful login, return Json(true) from the controller and in the success callback of ajax, redirect to the Products action

[HttpPost]
public ActionResult Login(UserViewModel user)
{
     // authentication code here

     return Json(true);
}

JS:

self.SubmitLocation = function() {
  var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));

  $.ajax({
    ur: '@Url.Action("Login", "Home")',
    type: 'post',
    data: jsonData,
    contentType: 'application/json',
    success: function(data) {
      if (data)
        location.href = '@Url.Action("Products", "Product")'; // redirect
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM