张贴到MVC控制器,视图模型保持空 [英] Posting to MVC Controller, ViewModel stays null

查看:136
本文介绍了张贴到MVC控制器,视图模型保持空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的ASP.NET MVC控制器动作和视图模型:

I have this ASP.NET MVC controller action and viewmodel:

public JsonResult Upload(UploadModel MyModel)
{
    //do stuff with MyModel
}

public class UploadModel
{
    public string Name;
}

而在角,提交一个表单,这个动作的方法:

And in Angular, a method for submitting a form to this action:

function onSubmit() {
     console.log(vm.model);
     $http.post('/Home/Upload', vm.model).
     then(function (response) 
     { 
         // do stuff with response 
     }); 
};

当我登录vm.model,它看起来像这样:

When I log vm.model, it looks like this:

{ Name : "Some cool name" }

它看起来在请求负载完全相同。但是,当我张贴此对象上传方法,名称显示为空值。然而,当我改变上传方法,接受只是一个字符串,而不是一个视图模型:

It looks exactly the same in the request payload. But when I post this object to the Upload method, Name appears to be null. However, when I change the Upload method to accept just a string instead of a viewmodel:

public JsonResult Upload(String Name)
{
    //do stuff with Name
}

和发布完全相同的对象给它,它确实得到认可。

And post the exact same object to it, it does get recognized.

这是怎么回事?为什么不承认MVC我JS对象作为视图模型?

What is going on? Why isn't MVC recognizing my JS object as a viewmodel?

推荐答案

名称是一个领域,不是一个属性(没有的getter / setter),使 DefaultModelBinder 不能设置的值。将其更改为

Name is a field, not a property (no getter/setter) so the DefaultModelBinder cannot set the value. Change it to

public class UploadModel
{
    public string Name { get; set; }
}

这篇关于张贴到MVC控制器,视图模型保持空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆