如何将多个参数从表单传递到Asp.net MVC内核中的控制器?

问题描述 投票:0回答: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();
        }
asp.net .net asp.net-core routing asp.net-core-mvc
1个回答
0
投票

尝试一下:

[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

© www.soinside.com 2019 - 2024. All rights reserved.