简体   繁体   中英

How to change display value of items in data model?

On the list of users, I would like to display the name of their role instead of roleId. Currently the data is loaded in the following form:

@model IEnumerable<DemoRes.Models.User>

<div id="divUsers">
    <h2>Users</h2>
    <table class="table">
        <tr>
            <th>Username</th>
            <th>Email</th>
            <th>Access Role</th>
            <th>Enabled</th>
            <th></th>
        </tr>
        <tbody data-bind="foreach: List">
            <tr>
                <td data-bind="text : Username"></td>
                <td data-bind="text : Email"></td>
                <td data-bind="text : Role"></td>
                <td data-bind="text : IsActive"></td>
            <td>


</td>
            </tr>
        </tbody>
    </table>
</div>

The role property of User objects is an int value (0 - Admin, 1 - Member).

Currently in the form thus in the column "Access Role", integer value is displayed.

What I would like to do is replace the integer value with belonging string (either "Admin" or "Member") . Does anyone know what is the best way to accomplish that, given that the roles could be in general represented with arbitrary list or dictionary? How should the list (or dictionary) of roles be passed to form in this case (for example, using ViewBag, by modifying view model...)?

Thanks!

Best practice here is to put it in the view model, then you can reference it in your knockout:

public string RoleName { get; set; }

Then populate it with your data (in your controller/business logic/model population code), then you can do:

<td data-bind="text : RoleName"></td>

As an aside from that, as @David mentioned, it looks like you're displaying passwords, which aside from the fact is terrible security , it also means that you're storing them unencrypted, which means that if someone gains access to your database, they get everyone's passwords, not good .

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