【问题标题】:How to pass string from a View to a controller in mvc如何将字符串从视图传递到mvc中的控制器
【发布时间】:2019-01-02 05:58:41
【问题描述】:

此 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代码:

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

代码未按预期工作,因为 id 为 null。

有人可以指导吗?

【问题讨论】:

  • this.id 可能包含 null - 也无需使用 contentType,因为您可以像 data: { id: "someid" } 一样传递它。

标签: javascript jquery html asp.net asp.net-mvc


【解决方案1】:
$.ajax({
  type: 'POST',
  url: '/brandsOfACategory',
  contentType: 'application/json; charset:utf-8',
  data: { 'id': id }
})

【讨论】:

    【解决方案2】:

    Ajax 代码

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

    更多关于ajax的信息link

    ASP.Net中的参数绑定 link

    【讨论】:

      【解决方案3】:

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

      "link1"
      

      要使模型绑定起作用,有效负载应具有键值格式,以便将值映射到与键具有相同值的参数。

      由于它是一个简单的值,因此您不必将 JSON 字符串化版本和contentType 作为application/json 发送。只需将 JS 对象发送为data。确保您发送的 JavaScript 对象的键/属性名称与您的操作方法参数名称 (id) 相同,它会起作用。

      假设您的锚标记具有有效的Id 属性值,因此this.id 表达式返回有效的字符串值。

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

      在脚本中,您可能还想停止正常的点击行为,以防止页面导航到 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);
          })
      });
      

      这会将id=myId 之类的值作为请求的表单数据发送。由于您没有明确指定 contentType,它将使用默认的 application/x-www-form-urlencoded

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 2023-03-29
        • 2014-04-01
        • 1970-01-01
        相关资源
        最近更新 更多