【问题标题】:Parameters not passing through to MVC Controller with Guid ID参数未通过 Guid ID 传递到 MVC 控制器
【发布时间】:2013-01-03 23:18:07
【问题描述】:

我在 .net 4.0 Web 表单 Web 应用程序上使用 Web api 执行以下控制器操作。

public dynamic Post(Guid id, string adminNotes = "", string artNotes = "")
        {
            dynamic response = new ExpandoObject();
            response.Success = false;
            Udac udac = CustomerUdacs.Where(x => x.EditKey == id).FirstOrDefault();
            if (udac != null)
            {
                udac.AdminNotes = adminNotes.Trim();
                udac.ArtNotes = artNotes.Trim();
                response.Success = true;
            }
            return response;
        }

我正在使用 jQuery ajax() 来发布数据。我使用 Guid 作为我的 id(存储在我的 javascript 中的 ajax_edit_key 中)。当我使用这个时:

$.ajax({
                    type: "POST",
                    url: "/api/notes/"+ajax_edit_key,
                    data: { adminNotes: $("#tbEditNotesAdmin").val(), artNotes: $("#tbEditNotesArt").val() }
                }).done(function (data) {
                    if (data.Success) {
                        $("#tbEditNotesAdmin").val(''); //td.id-notes-admin
                        $("#tbEditNotesArt").val(''); //td.id-notes-art
                        ajax_edit_key = '';
                        $dialog.dialog("close");
                    }
                }).fail(function () {
                    alert('fail');
                });

它调用了该操作,但我的 adminNotes 和 artNotes 作为空字符串从浏览器传递过来。

如果我更改 url 以在查询字符串中包含参数,它可以正常工作。

url: "/api/notes/"+ajax_edit_key+"?"+ "adminNotes="+$('#tbEditNotesAdmin').val()+"&artNotes="+$('#tbEditNotesArt').val()
//data: { adminNotes: $("#tbEditNotesAdmin").val(), artNotes: $("#tbEditNotesArt").val() }

这是为什么?我怎样才能让它使用数据参数

【问题讨论】:

    标签: asp.net jquery asp.net-web-api


    【解决方案1】:

    这里的问题是 WebAPI 引擎如何解析多个参数的方式。它只能解析一个参数,默认来自body请求,你有两个。

    解决办法是:

    对于第二个选项,您只需创建模型:

    public class NotesModel
    {
        public string AdminNotes { get; set; }
        public string ArtNotes { get; set; }
    }
    

    并将您的操作签名更改为:

    public dynamic Post(Guid id, NotesModel model)
    

    而且你不需要改变你的 JS。

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多