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

Javascript 如何在mvc中将字符串从视图传递到控制器,javascript,jquery,html,asp.net,asp.net-mvc,Javascript,Jquery,Html,Asp.net,Asp.net Mvc,此JavaScript代码用于将字符串从视图传递到控制器中的操作: <script type="text/javascript"> $(document).on('click', 'a', function () { $.ajax({ type: 'POST', url: '/brandsOfACategory', contentType: 'application/json; chars

此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>
public ActionResult brandsOfACategory(string id)
    {
        return View();
    }
代码未按预期工作,因为id为null


有人可以指导吗?

使用当前代码,在进行ajax调用时,请求负载只有一个字符串值。例如,如果单击的链接具有
Id
属性值“link1”,它将发送以下字符串作为ajax调用的请求负载。(如果打开开发工具->网络选项卡,可以看到这一点)

对于要工作的模型绑定,有效负载应该具有键值格式,以便将值映射到与键具有相同值的参数

因为它是一个简单的值,所以不需要将JSON字符串化版本和
contentType
作为
application/JSON
发送。只需将JS对象作为
数据发送即可。确保发送的JavaScript对象的键/属性名称与操作方法参数名称(
id
)相同,并且该对象将正常工作

假设锚定标记具有有效的
Id
属性值,那么
this.Id
表达式将返回有效的字符串值

<a href="/SomeUrl" id="myId">MyLink</a>
这将发送像
id=myId
这样的值作为请求的表单数据。由于您没有明确指定contentType,因此它将使用默认的
应用程序/x-www-form-urlencoded


如果用户单击的链接没有
Id
属性,代码将不发送任何值,因为
this.Id
将返回空字符串,服务器端的参数值将为null。

Ajax code

$.ajax({
  type: 'POST',
  url: '/brandsOfACategory',
  contentType: 'application/json; charset:utf-8',
  data: { 'id': id }
})
$.ajax({
    url: "controllerurl",
    type: "POST",
    data: {
        id: "123"
    },
    dataType: "json",
    success: function(result) {
        //Write your code here
    }
});
有关ajax的更多信息


ASP.Net中的参数绑定

此.id
可能包含null-也无需使用
contentType
,因为您可以像
数据:{id:“someid”}
一样传递它。
$.ajax({
  type: 'POST',
  url: '/brandsOfACategory',
  contentType: 'application/json; charset:utf-8',
  data: { 'id': id }
})
$.ajax({
    url: "controllerurl",
    type: "POST",
    data: {
        id: "123"
    },
    dataType: "json",
    success: function(result) {
        //Write your code here
    }
});