【问题标题】:MVC API controller's complex object not getting populated from jquery ajax callMVC API 控制器的复杂对象未从 jquery ajax 调用中填充
【发布时间】:2013-01-24 17:23:19
【问题描述】:

我正在尝试调用 POST API 控制器。控制器被调用,但复杂对象为空。我已经运行了 Fiddler,并且该对象甚至来自那里。我做错了什么?

我的 C# 对象

public class RegisterUser
{
    public Guid PersonId { get; set; }
    public string Email { get; set; }
    public string Business { get; set; }
    public string EmployeeNumber { get; set; }
    public string UserName { get; set; }
}

API 后控制器

public HttpResponseMessage Post(RegisterUser user)
{
   //This is where the problem is. Everything in user is null 
   //even though I can see it coming through on Fiddler.
}

Javascript 代码

function User(personId, userName, email, business, employeeNumber) {
   this.PersonId = personId;
   this.Email = email;
   this.Business = business;
   this.EmployeeNumber = employeeNumber;
   this.UserName = userName;
}

function RegisterUser(url) {
   var createdUser = new User("b3fd25ba-49e8-4247-9f23-a6bb90a62691", "username", "email", "business", "56465");
   $.ajax(url, {
       data: JSON.stringify({ user: createdUser }),
       type: "post",
       contentType: "application/json"
  });
}

Web API 路由配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "RegisterApi",
            routeTemplate: "api/{controller}/{user}"
        );
    }
}

【问题讨论】:

  • AJAX 调用是异步的,看起来您是在返回任何数据之前执行结果代码。
  • 问题是API控制器RegisterUser对象没有被填充......js ajax甚至还没有返回。
  • 你的动作有HttpPost属性吗?
  • 它是一个 mvc web api 控制器。您不必再指定了。

标签: c# asp.net-mvc jquery asp.net-mvc-4


【解决方案1】:

createdUser 已经以正确的格式包含 Web.Api 所需的数据,无需将其包装在混淆模型绑定器的 user 属性中。

只需写data: JSON.stringify(createdUser),它应该可以正常工作:

function RegisterUser(url) {
   var createdUser = new User("b3fd25ba-49e8-4247-9f23-a6bb90a62691", "username", "email", "business", "56465");
   $.ajax(url, {
       data: JSON.stringify(createdUser),
       type: "post",
       contentType: "application/json"
  });
}

模型绑定的原理很简单,除非您在 JS 和 C# 对象中具有匹配的属性名称和对象结构,并且它应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2017-08-24
    • 2018-01-22
    • 2018-11-12
    相关资源
    最近更新 更多