【问题标题】:How can I redirect from View to controller method that has to return another view如何从 View 重定向到必须返回另一个视图的控制器方法
【发布时间】:2023-03-30 21:22:01
【问题描述】:

我有一个视图,其中包含一个按钮,单击该按钮必须重定向到控制器中返回另一个视图的方法。问题是这个方法接受参数,我不知道每次点击它正确重定向的按钮时如何传递它们?

方法:

public virtual ActionResult Classificate (int firstArg, int secondArg)
        {
            //Some logics
            return View(MVC.Document.Views.MyView, model: result);
        }

html:

<div id="my-button-id">Button</>

并且在视图的 html 中,我希望能够编写一个 js 代码,在每次 "#my-button-id" 单击时使用我传递给函数的 2 个参数重定向到方法在控制器中。

伪解码:

$("#my-button-id").on('click',function(){
    redirectToOtherView(4, 5)
});

function redirectToOtherView(fArg, sArg){
    //this function to redirect to the Classificate method in the Document controller
    //by passing the arguments
}

【问题讨论】:

  • 您想使用 ajax 或普通页面刷新/重定向加载视图?

标签: jquery asp.net-mvc asp.net-mvc-routing


【解决方案1】:

你需要pass the parameter as query string for GET request和正常的页面重定向

function redirectToOtherView(fArg, sArg){   

 var queryString="firstArg="+fArg+"&secondArg=sArg";

 window.location.href="/ControllerName/Classificate/?"+queryString

}

对于 ajax GET

$.get(url, {firstArg:fArg, secondArg:sArg}, 
    function(result){
    $('#container').html(result);
    }
);

或者 ajax POST --> 在 Controller 中添加 [HttpPost]

$.post(url, {firstArg:fArg, secondArg:sArg}, 
    function(result){
        $('#container').html(result);
    }
);

【讨论】:

  • 这个好像可以,但是我在i-net上读到,一些老版本的浏览器不支持它,比如IE 6。你怎么看?
  • @mathinvalidnik,不支持什么功能?可以贴链接吗?
  • 只是 window.loacation.href。你知道我怎么能用ajax调用来做到这一点,因为我试图做$ .ajax {}但它不起作用。我在控制器[HttpGet]中创建了这个方法,但它只是没有重定向到视图。
  • @mathinvalidnik,ajax 永远不会进行重定向。它只会使用javascript从服务器加载数据。它不会做任何重定向
猜你喜欢
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
相关资源
最近更新 更多