简体   繁体   中英

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. 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:

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. This does not need to be sent back to the GET action when generating the report.

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. I then generate a full viewmodel and return it back to the same view.

Some problems I see:

Dropdown of EntityAccounts is submitted back to the action (I can see it in the query string). 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]
public IEnumerable<EntityAccountDTO> EntityAccounts { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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