简体   繁体   中英

Asp.Net Core MVC view component with Html.Checkboxfor lambda (override model)

I need a way of referencing a different model in my view component where I'm trying to bind an Html helper object (checkboxfor).

@model Microsoft.WindowsAzure.Storage.Table.TableResult

@{ 
    var result = Model.Result as TenantSettingsModel;
}
    <form asp-controller="Settings" asp-action="SaveSettings" method="post">
    <table border="0">
    <tr>
        <td><label for=@result.PartitionKey>Your API Key: </label> </td>
        <td>@result.PartitionKey</td>
    </tr>
    <tr>
        <td><label for=@result.RowKey>Domain Name: </label></td>
        <td>@result.RowKey</td>
    </tr>
    <tr>
        <td><label for="@result.AutoUpdateNodes">Auto Update Nodes: </label> 
    </td>
        <td>@Html.CheckBoxFor(m => m.AutoUpdateNodes)</td>

    </tr>

MVC thinks my lambda expression is referring to my "TableResult" model versus the "TenantSettingsModel" where my "AutoUpdateProperty" exists.

Edit: If I cast TableResult to TenantSettingsModel in the controller, then remove my model statement in the view, I get an MVC runtime error stating the following:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.WindowsAzure.Storage.Table.TableResult', but this ViewDataDictionary instance requires a model item of type 'TeamsAnalyzer.Models.TenantSettingsModel'.

This is why my view had the following code:

var result = Model.Result as TenantSettingsModel;

In my opinion, you should cast the model at controller level which should return the model directly,

. . var tenantSettingViewModel = tableResult.Result as TenantSettingsModel; return View(tenantSettingViewModel);

This way you don't have to cast the object at View level and you can also leverage HtmlHelpers of MVC with models directly.

The answer here is two fold:

  1. I needed to cast the TableResult.Result as TenantSettingsModel in the controller as follows:

     TableResult retrievedResult = await tableName.ExecuteAsync(retrieveOperation); return View(retrievedResult.Result as TenantSettingsModel);
  2. I needed to remove the @model reference to TableResult in the view component view and replace it with the correct reference as follows:

     @model TeamsAnalyzer.Models.TenantSettingsModel

I could then set my lambda expression as follows:

@Html.CheckBoxFor(m => m.AutoUpdateNodes)

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