vpp090
vpp090

Reputation: 1073

Can you pass an object to MVC post action?

I have this MVC post action

 [HttpPost]
  public ActionResult PostHere(SomeRandomResult result)
{
 return View();
}

Object I would want to pass:

public class SomeRandomResult
{
public string firstName {get; set;}
public string lastName {get; set;}
}

View:

<form method="post">
    <input type="text" id="first-name" name="firstName">
    <input type="text" id="last-name" name="lastName">
    <input type="submit" value="click me"/>
</form>

The question is when I click submit in the form, I want the values in SomeRandomResult to be automatically populated. When I click submit now, the object in the post method is null. How do I get the values from firstName and lastName?

Upvotes: 0

Views: 788

Answers (1)

NotTheBatman
NotTheBatman

Reputation: 132

Your post body should be some kind of object notation, JSON is popular

{
  "firstName": "John",
  "lastName": "Wick"
}

Then your signature becomes

public ActionResult PostHere([FromBody]SomeRandomResult result)

Upvotes: 4

Related Questions