Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

asp.net mvc - How can I send multiple data to the Controller with Vue js in .NET 5

This is my Controller

    [HttpPost]
    public JsonResult Kaydet([FromBody] int Id, string FirstName, string LastName, string Address)
    {
        return Json(new { status = 0 });
    }

This is my View

   fetch('/Student/Kaydet', {
         method: 'post',
         headers: {
                 'Content-Type': 'application/json'
         },
         body: { "Id": 1, "FirstName": 'a', LastName: 'b', Address: 'c' }
    })

Status Code = 200,but Controller is null

question from:https://stackoverflow.com/questions/65933354/how-can-i-send-multiple-data-to-the-controller-with-vue-js-in-net-5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to define a model to get the data from the request body. The [FromBody] attribute can only be used once in an action.

Model:

public class ViewModel
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
}

View:

fetch('/Home/Kaydet', {
    method: 'post',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ "Id": 1, "FirstName": 'a', "LastName": 'b', "Address": 'c' })
})

Controller:

[HttpPost]
public JsonResult Kaydet([FromBody]ViewModel viewModel)
{
    return Json(new { status = 0 });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...