如何将多个参数从表单传递到 Asp.net MVC 核心中的控制器?
How to I pass multiple parameters from a form to a controller in Asp.net MVC core?
您好,我正在尝试从表单中获取文本框并将它们作为参数插入到控制器中
这是我的表格
@{
ViewData["Title"] = "AddCar";
}
<h1>AddCar</h1>
<form asp-action="AddCar" method="post">
<div class="text-danger">@Validation.errorMessage</div>
<label>Make/Model: </label><br />
<input type="text" name="makeModel" value="Buick" /><br />
<label>Year: </label><br />
<input type="text" name="year" value="1998" /><br />
<label>Color: </label><br />
<input type="text" name="color" value="Red" /><br />
<label>Price: </label><br />
<input type="text" name="price" value="123123" /><br />
<label>Milage: </label><br />
<input type="text" name="milage" value="112312" /><br />
<button type="submit">Search</button>
</form>
这是我的控制器
[HttpPost]
[Route("[area]/AddCar/{makeModel}/{milage}/{year}/{color}/{price}")]
public IActionResult AddCar(String makeModel, String milage, String year, String color, String price)
{
Car car = new Car(year, makeModel, price, milage, color);
return View();
}
试试这个:
[HttpPost]
[Route("[area]/AddCar")]
public IActionResult AddCar([FromForm] Car car)
{
...
return View();
}
但最佳做法是使用视图模型。检查此页面
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1
您好,我正在尝试从表单中获取文本框并将它们作为参数插入到控制器中 这是我的表格
@{
ViewData["Title"] = "AddCar";
}
<h1>AddCar</h1>
<form asp-action="AddCar" method="post">
<div class="text-danger">@Validation.errorMessage</div>
<label>Make/Model: </label><br />
<input type="text" name="makeModel" value="Buick" /><br />
<label>Year: </label><br />
<input type="text" name="year" value="1998" /><br />
<label>Color: </label><br />
<input type="text" name="color" value="Red" /><br />
<label>Price: </label><br />
<input type="text" name="price" value="123123" /><br />
<label>Milage: </label><br />
<input type="text" name="milage" value="112312" /><br />
<button type="submit">Search</button>
</form>
这是我的控制器
[HttpPost]
[Route("[area]/AddCar/{makeModel}/{milage}/{year}/{color}/{price}")]
public IActionResult AddCar(String makeModel, String milage, String year, String color, String price)
{
Car car = new Car(year, makeModel, price, milage, color);
return View();
}
试试这个:
[HttpPost]
[Route("[area]/AddCar")]
public IActionResult AddCar([FromForm] Car car)
{
...
return View();
}
但最佳做法是使用视图模型。检查此页面 https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1