BindAttribute to check json objects from MVC

时间:2019-04-08 13:47:04

标签: c# asp.net-mvc post data-binding

During an MVC Post, I need to ensure that only the data I need is coming through to my method and all other information is ignored, I have found the BindAttribute which works well for Form Posting, e.g.

[HttpPost()]
[Route("name")]
public void GetName([Bind(include:"Name")] NameAddress value)

This only checks for FormBindings, I'd like to check for JSON object bindings, something like this:

[HttpPost()]
[Route("name")]
public void GetName([BindJson(include:"Name")] NameAddress value)

If the following were passed on the Body only the name would be set:

{
    "id": 1,
    "Address": "somewhere",
    "Name": "Peter"
}

1 个答案:

答案 0 :(得分:0)

创建视图模型

public UserVM
{

public stirng Name {get;set;} 

}

实际使用方法

[HttpPost()]
[Route("name")]
public void GetName(UserVM value)
{

string name = value; // Get the Name


}

选中this,从客户端Json发布Javascript数据。