javascript - 使用 jquery 将数据发送到 MVC Controller

标签 javascript c# jquery asp.net asp.net-mvc

我有一个 ASP.NET MVC3 应用程序,当用户点击我的 anchor 标记时,我想将 3 条数据发送到一个操作:

 <a onclick='editDescription(<#= DocID,FileName,Description #>)'></a>

这是调用我的操作的 javascript:

   function editDescription(docId,fileName,description) {
     var url = "@Url.Content("~/OrderDetail/_EditDescription/")" + docId+'/'+
     fileName + '/' + description;
    //do the rest}

我的行动:

  public ActionResult _EditDescription(string id,string filename, string descritpion)

我关心的是 FileName 和 Description,因为它们可能很长而且我不希望 url 像这样显示:

 http://localhost/OrderDetail/_EditDescription/123/some long filename.pdf/this is a    long description for the name

如何将我的数据发送到我的操作,而不必像查询字符串一样发送它?谢谢

最佳答案

您可以使用 jQuery $.ajax 方法:

<div id="what-I-want-updated">

  <input id="whatever-the-id-is" type="text" value="@Model.ID" />
  <br /> 
  <input id="whatever-the-filename" type="text" value="@Model.Filename" />
  <br />
  <input id="whatever-the-description" type="text" value="@Model.Description" />
  <br />
  <button id="whatIsClicked">Update!</button>

</div> <!-- /#what-I-want-updated -->

<script>

    // You're probably clicking something to initiate update 
    var $whatIsClicked = $('#whatIsClicked');

    // .live persists on the page even after other ajax calls
    // So when the thing is clicked
    $whatIsClicked.live('click', function() {

       // Grab the information needed to update
       var theId = $('#whatever-the-id-is').val(); //Or it could be .text()
       var theFilename = $('#whatever-the-filename').val();
       var theDescript = $('#whatever-the-description').val();

       // Let's edit the description!
       $.ajax({
         type: "POST",
         url: "OrderDetail/_EditDescription", // the method we are calling
         contentType: "application/json; charset=utf-8",
         data: {id: theId, filename: theFilename, description: theDescript},
         dataType: "json",
         success: function (result) {
             alert('Yay! It worked!');
             // Or if you are returning something
             alert('I returned... ' + result.WhateverIsReturning);                    
         },
         error: function (result) {
             alert('Oh no :(');
         }
     });
    });
</script>

即使它仍然有效,请确保将 Controller 方法更改为:

[HttpPost]
public ActionResult _EditDescription(string id, string filename, string descritpion)

关于javascript - 使用 jquery 将数据发送到 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016388/

相关文章:

javascript - Socket.io 从 Node 中的多个套接字接收数据

c# - 搜索中的 ":"是什么意思(名称,onlyActive : true)?

javascript - 切换具有相同类但单独的 div,而不是一次全部?

javascript - jQuery 中计算动态隐藏字段

javascript - watir ruby​​ 文件上传 windows 交互

javascript - JavaScript 语言服务遇到错误并已关闭

javascript - 在 Google Chrome 中设置 JavaScript 超时限制

c# - EF4 和多个抽象级别

c# - 德国文化 - 用逗号从 JSON 中获取双数

javascript - 下拉菜单的 CSS 与 Javascript(或库 js)