简体   繁体   English

如何使用Knockout.js在MVC控制器之间移动?

[英]How to move between MVC controllers using knockout.js?

I have an issue with moving from one MVC controller to another. 从一个MVC控制器转移到另一个MVC控制器时遇到问题。 I am new to MVC/Knockout combination and trying to find a best way. 我是MVC /淘汰赛组合的新手,正在尝试寻找最佳方法。

I have a HomeController that does some login processes. 我有一个HomeController,它执行一些登录过程。 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" 在选择了某个选项后,通过按下带有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 : 这将其带入MVC控制器中的代码:

    [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. 通过代码调试,我看到它毫无例外地被传递到了Product控制器甚至是Products视图。 However the page on the browser itself remains on the original HomeController/Login view. 但是,浏览器本身的页面仍保留在原始的HomeController / Login视图中。 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. 我也尝试过从同一个HOmeController返回一个不同的视图,而不是RedirectToAction,并且它仍然相同。

You can't return RedirectToAction() or return View() to an ajax call. 您不能return RedirectToAction()return View()给ajax调用。 Upon successful login, return Json(true) from the controller and in the success callback of ajax, redirect to the Products action 成功登录后,从控制器return Json(true)并在ajax的success回调中,重定向到Products操作

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

     return Json(true);
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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