James
James

Reputation: 1261

Convert current model to JSON in the Task<IActionResult> OnPostAsync method within the MVC.NET Core application

I am supposed to create a functionality where the MVC.NET Core application submits the JSON request through a Web API within the public async Task OnPostAsync(Request request) method

public async Task<IActionResult> OnPostAsync(Request request)
{    
   if(request.OwnershipActivity == null || request.OwnershipActivity.Ownership == null)
    {
        ModelState.AddModelError("OwnershipAnswer", "You must select an option.");               
    }
    if (!ModelState.IsValid)
    {                
        return Page();
    }
    //Do POST to database then redirect to Index
    //Submit JSON
    creturn RedirectToPage("../Index");
}

How do I convert a current Model(Form) into a JSON?

Thank you for your help

Upvotes: 1

Views: 4610

Answers (2)

James
James

Reputation: 1261

It turned out to be beyond simple

string requestJson = JsonConvert.SerializeObject(request);

Upvotes: 2

Thiago Moises
Thiago Moises

Reputation: 29

Try use this

public async Task<IActionResult> OnPostAsync(Request request)
{    
    ...
    return Json(yourObject);
}

See the link of the documentation

Upvotes: 1

Related Questions