简体   繁体   English

提交表单时,ASP.NET Core排除viewmodel的属性

[英]ASP.NET Core exclude property of viewmodel when submitting form

I have a controller/action/view which contains a form to generate reports. 我有一个控制器/操作/视图,其中包含用于生成报告的表单。

public async Task<IActionResult> Report(int? entityId, DateTime fromDate, DateTime toDate)
{
}

On HTTP GET, I first check if entityId is empty. 在HTTP GET上,我首先检查entityId是否为空。 If it is, I assume the user is navigating to /report/ to populate the form fields to generate a report, so I just return a partial viewmodel containing information about dropdowns, etc: 如果是这样,我假设用户导航到/report/来填充表单字段以生成报告,因此我只返回一个包含有关下拉列表等信息的局部viewmodel:

public class ReportViewModel
{
    // ...

    // this is populated as user has to choose one of these via dropdown
    // to generate a report.  
    public IEnumerable<EntityAccountDTO> EntityAccounts { get; set; }

    // ... other properties left unpopulated at this point
}

Choosing an EntityAccounts option from the dropdown populates two date pickers with values that will be used for fromDate and toDate in the /report/ action parameters. 从下拉列表中选择EntityAccounts选项,将使用/report/ action参数中的fromDatetoDate值填充两个日期选择器。 This does not need to be sent back to the GET action when generating the report. 生成报告时,不需要将其发送回GET操作。

The form in the view is then populated and the user clicks on "Get Report". 然后,填充视图中的表单,用户单击“获取报告”。 At this point the same GET action is hit, but entityId.HasValue is true , fromDate and toDate have values from the dropdowns, so I have all the info to generate the report. 此时,将执行相同的GET操作,但是entityId.HasValuetruefromDatetoDate具有下拉菜单中的值,因此我具有生成报告的所有信息。 I then generate a full viewmodel and return it back to the same view. 然后,我生成一个完整的viewmodel并将其返回到同一视图。

Some problems I see: 我看到一些问题:

Dropdown of EntityAccounts is submitted back to the action (I can see it in the query string). EntityAccounts下拉EntityAccounts被提交回该操作(我可以在查询字符串中看到它)。 As mentioned before this is only there for the user to initially select a value, I don't need it submitted back to the action.. How do I prevent it from being submitted? 如前所述,这只是供用户最初选择一个值,我不需要将其提交回操作。如何防止它被提交?

    <label asp-for="@Model.EntityAccounts">Entity accounts</label>
    <!-- Input -->
    <select asp-for="@Model.EntityAccounts" class="form-control" data-toggle="select">
        @foreach () { //... generate <option>s }                           
    </select>

You can use the [BindNever] attribute on your view model property to prevent the model binder from setting it. 您可以在视图模型属性上使用[BindNever]属性,以防止模型绑定程序进行设置。

[BindNever]
public IEnumerable<EntityAccountDTO> EntityAccounts { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM