简体   繁体   English

如何将字符串从视图传递到 mvc 中的控制器

[英]How to pass string from a View to a controller in mvc

This JavaScript code is being used to pass a string from a view to an action in a controller:此 JavaScript 代码用于将字符串从视图传递到控制器中的操作:

<script type="text/javascript">
    $(document).on('click', 'a', function () {
        $.ajax({
            type: 'POST',
            url: '/brandsOfACategory',
            contentType: 'application/json; charset:utf-8',
            data: JSON.stringify(this.id)
        })
    });
</script>

brandsOfACategory code in the controller:控制器中的brandOfACategory 代码:

public ActionResult brandsOfACategory(string id)
    {
        return View();
    }

Code is not working as expected as id is coming as null.代码未按预期工作,因为 id 为空。

Can someone please guide?有人可以指导吗?

$.ajax({
  type: 'POST',
  url: '/brandsOfACategory',
  contentType: 'application/json; charset:utf-8',
  data: { 'id': id }
})

Ajax Code阿贾克斯代码

$.ajax({
    url: "controllerurl",
    type: "POST",
    data: {
        id: "123"
    },
    dataType: "json",
    success: function(result) {
        //Write your code here
    }
});

For more info about ajax link有关 ajax链接的更多信息

Parameter binding in ASP.Net link ASP.Net 链接中的参数绑定

With your current code, when the ajax call is made, the request payload has only a string value.使用您当前的代码,在进行 ajax 调用时,请求负载只有一个字符串值。 For example, if your clicked link has an Id attribute value "link1", it will send the below string as the request payload for your ajax call.(You can see this if you open up your dev tools->network tab)例如,如果您单击的链接具有Id属性值“link1”,它将发送以下字符串作为您的 ajax 调用的请求负载。(如果您打开开发工具->网络选项卡,您可以看到这一点)

"link1"

For model binding to work, the payload should have a key-value format so that the value will be mapped to the parameter with the same value as the key.为了使模型绑定起作用,有效负载应具有键值格式,以便将值映射到与键具有相同值的参数。

Since it is a simple value, you do not need to necessarily send the JSON stringified version and the contentType as application/json .由于它是一个简单的值,因此您不必将 JSON 字符串化版本和contentType作为application/json Simply send the JS object as data .只需将 JS 对象作为data发送。 Make sure you are sending a JavaScript object which has the key/property name same as your action method parameter name( id ) and it will work.确保您发送的 JavaScript 对象的键/属性名称与您的操作方法参数名称( id )相同,并且它会起作用。

Assuming your anchor tag has a valid Id attribute value so that the this.id expression returns the valid string value.假设您的锚标记具有有效的Id属性值,以便this.id表达式返回有效的字符串值。

<a href="/SomeUrl" id="myId">MyLink</a>

In the script, you probably want to stop the normal click behavior as well to prevent the page from navigating to the href attribute value.在脚本中,您可能还想停止正常的点击行为,以防止页面导航到 href 属性值。

$(document).on('click', 'a', function (e) {
    e.preventDefault();

    $.ajax({
        type: 'POST',
        url: '/brandsOfACategory',
        data: { id :this.id } 
    }).done(function (res) {
        console.log('result from ajax call',res);
    })
});

This will send the value like id=myId as the Form Data for the request.这将发送像id=myId这样的值作为请求的表单数据。 Since you are not specifying the contentType explicitly, it will use the default application/x-www-form-urlencoded由于您没有明确指定 contentType,它将使用默认的application/x-www-form-urlencoded

If the link user clicked does not have an Id attribute, the code will send no value because this.id will return an empty string and your parameter value at server side will be null.如果用户点击的链接没有Id属性,代码将不会发送任何值,因为this.id将返回一个空字符串并且您在服务器端的参数值为 null。

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

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