【问题标题】:Passing form data to a model when using multiple models in the same view在同一视图中使用多个模型时将表单数据传递给模型
【发布时间】:2021-12-26 14:26:03
【问题描述】:

当我在一个视图中有多个模型时,您如何将表单数据传递给模型(在我的控制器中使用)?

I used this tutorial for multiple models in a view.

索引视图和表单(简化):

@using FlightBooker
@model dynamic

<form asp-controller="Home" asp-action="Search" method="post">
                <div class="form-group">
                    <label for="fromAirport">Flying from:</label>
                <select class="form-control">
                    @foreach (Airport airport in Model.Airports)
                    {
                        <option >@airport.AirportCode</option>
                    }

                </select>
                <div class="form-group">
                    <label for="toAirport">Flying to:</label>
                    <select class="form-control">
                        @foreach (Airport airport in Model.Airports)
                        {
                            <option>@airport.AirportCode</option>
                        }

                    </select>
                </div>
                    <label for="fromAirport">Departure Date:</label>
                    <br />
                    <input type="date" / id="date" name="date">
                    <br />
                    <label for="fromAirport">No. passengers:</label>
                    <select class="form-control" id="passengers" name="passengers">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                    </select>
                    <button type="submit" class="btn btn-primary mt-3">Search Flights</button>
                </div>
            </form>

我在看这个教程,这个部分:Strongly type model binding to view。当我使用@model dynamic时,我不知道如何应用它。

或者我会更好地将视图模型创建为suggested here

【问题讨论】:

  • 制作一个名为“SearchViewModel”的ViewModel,添加与输入字段的html名称相同的属性,例如public class SearchViewModel { public datetime date {get;set;} }当你把它作为称为搜索的操作的参数将自动绑定到值。注意:在 html 中添加 select 的值

标签: asp.net-mvc .net-core


【解决方案1】:

好的,我会告诉你在这里做什么.....

模型用于将数据从控制器渲染到视图。

如果您想将数据从视图传递到控制器,有一些更简单的方法...

第一步:

将所有的html input/select元素设置为Name的值

例子:

  <select class="form-control" name"AirportsDdl">
            @foreach (Airport airport in Model.Airports)
            {
                <option value="@airport.AirportCode">@airport.AirportCode</option>
            }

        </select>

<input type="date" / id="date" name="date">

注意 Select 必须有一个值

第二步

然后你制作一个像这样的 ViewModel

public class SearchViewModel
{
public datetime date {get;set;}
public int AirportsDdl {get;set;}
}

第三步:

然后在你的行动中:

ActionResult Search(SearchViewModel sreachData)
{
//put your filter here
return view();
}

那么你们都准备好了

【讨论】:

  • 我已经完成了第 2 步和第 3 步,但我错过了第 1 步。看到它像这样布置有很大帮助,谢谢:)
猜你喜欢
  • 2011-12-21
  • 2011-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多