如何在MVC应用程序中传递Id值给window.location.href

How to pass Id value to window.location.href in MVC application

本文关键字:值给 Id window location href MVC 应用程序      更新时间:2023-09-26

目前我正在MVC应用程序上工作,因为我需要将页面呈现给MVC应用程序中的另一个动作,因此我需要将Id参数传递给该动作。

这是我的代码。

var CardCode=$('#CardCode').val();
if (str.substr("successfully")) {
    window.location.href='@Url.Action("EditPartner","MstPartner",new { id = CardCode})';
}

在代码中,当我传递值到那个id,即id=CardCode,那是不允许的,然后如何传递CardCode值到那个动作?

你的代码不能工作,因为你不能在那里传递一个变量。只有当value是硬编码

时才有效。
window.location.href='@Url.Action("EditPartner","MstPartner",new { id = "123"})';

你可以使用Replace方法

var CardCode=$('#CardCode').val();
if (str.substr("successfully")) {
    window.location.href='@Url.Action("EditPartner","MstPartner",new { id = "CC"})'.replace("CC",CardCode);
}

如果你想在客户端实现动态,你应该通过javascript来实现

function replaceUrlParam(url, paramName, paramValue){
    if(paramValue == null)
        paramValue = '';
    var pattern = new RegExp('''b('+paramName+'=).*?(&|$)')
    if(url.search(pattern)>=0){
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
}
var url = '@Url.Action("EditPartner","MstPartner",new { id = CardCode})';
var newUrl = replaceUrlParam(url,"Id","OtherCardCode");