Search code examples
c#asp.net.netwebapi

How to get values from all the input's of form in .net


this is my form

@{
ViewData["Title"] = "Add new customer";
}
<h1>Add new customer</h1>
<form method="post" action ="AddCustomer">
    <input name="customerID" placeholder="Add customer ID"/>
    <input name="customerName" placeholder="Add customer name"/>
    <input name="contactName" placeholder="Add contact name"></input>
    <input name="adress" placeholder="Add adress"></input>      
    <input name="city" placeholder="Add city"></input>
    <input name="postalCode" placeholder="Add postal code"></input>
    <input name="country" placeholder="Add country"></input>
    <input type="submit"></input>
</form>

it sends post request to this action

[HttpPost]
[ActionName("Simple")]
 public string AddCustomer([FromBody] string value)
  {
    return value;
  }

so how to get values from these inputs for me be able to send post request and create new customer using these values

Retrieving data from this form


Solution

  • Looks like you need to create a DTO (data transfer object).

    public class CustomerDto
    {
        public GUID CustomerID { get; set; }
        public string CustomerName { get; set; }
        public string ContactName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
    }
    

    And then you controller should be:

    [HttpPost]
    [ActionName("AddCustomer")]
    public IActionResult AddCustomer([FromForm] CustomerDto customer)
    {
        // use customer properties...
    }
    

    And then in the form add an enctype.

    <form method="post" action="AddCustomer" enctype="multipart/form-data">