【问题标题】:What to use instead window.location.href to call server method to show view用什么代替 window.location.href 来调用服务器方法来显示视图
【发布时间】:2023-04-03 16:01:02
【问题描述】:

当用户点击某个链接时,我有事件,该事件已经发生:

var dateParameter = "date=" + workday.DateString();                    
window.location.href = '@Url.Action("Index", "DateSelector")' + '?' + dateParameter; 

我不想使用这种调用,因为我想在浏览器的 URL 中隐藏参数。

我该怎么做?有没有可以使用 AJAX 的方法?

我在控制器中有如下所示的方法:

public ActionResult Index(string date)
{           
    // some logic...
    SomeViewModel vm = ...

    return View(vm);

}

如果我使用 AJAX,那么它不会加载想要的页面。

【问题讨论】:

    标签: javascript jquery asp.net ajax asp.net-mvc-4


    【解决方案1】:

    试试这个:

    var dateParameter = "date=" + workday.DateString(); 
    
    $.ajax({
            url: '/DateSelector/Index/' + dateParameter,
            type: 'POST',
            datatype: "json",
            contentType: "application/json; charset=utf-8"
    });
    

    希望对你有帮助:)

    【讨论】:

    • 它在 Contoller 中为日期传递 null:public ActionResult Index(string date) {...}
    • 尝试传递实际的日期字符串而不是 dateParameter,看看它是否将它发送到您的控制器
    【解决方案2】:

    你也可以试试这样传:

    window.location.href = '@Url.Action("Index", "DateSelector", 
                                                  new { date = dateParameter })';
    

    让我们把代码弄乱一下试试:

    var dateParameter = workday.DateString();
    
    var text = "@Url.Action("Index", "DateSelector", new { date = "dateParameter" })"
    text = text.replace("dateParameter", dateParameter);
    window.location.href = text;
    

    【讨论】:

    • 我想在浏览器的URL中隐藏参数。
    猜你喜欢
    • 2016-08-30
    • 2021-11-20
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多