开发者

Html.DisplayFor(modelItem => item.Status) - Passing it to a switch statement

开发者 https://www.devze.com 2023-03-20 14:10 出处:网络
I\'m pretty new to MVC, but I have the following code: <td> @Html.DisplayFor(modelItem => item.Status)

I'm pretty new to MVC, but I have the following code:

    <td>
        @Html.DisplayFor(modelItem => item.Status)
        @switch (item.Status)
        {
            case 0: Html.DisplayText("Requested");
                break;
            case 1: Html.DisplayText("In Progress");
                break;
            case 2: Html.DisplayText("Declined");
                break;
            default:
                Html.DisplayText("Unde开发者_开发问答fined");
                break;
        }
    </td>

It renders the "Html.DisplayFor" fine, this is an integer. But really I want to display the equivalent text based on the item.Status in that same position. But this is not working. I could change the way the original class handles the status in the Get and Set methods but how would I do it this way?


You could create a property on your ViewModel that does this logic for you. Such as

public string StatusDescription { 
    get { 
        switch (this.Status) {
            case 0: 
                return "Requested";
            case 1:
                return "In Progress";
            // yada yada yada
        }
    }
}

And in your view, replace the switch statement with

Html.DisplayFor(modelItem => item.StatusDescription);


I would create a declarative helper method (http://weblogs.asp.net/mikaelsoderstrom/archive/2010/10/06/declarative-helpers-in-razor.aspx) that displays the text based on the status. You can then call it similar to this in your view:

@Html.MyHelper(status)

Or even better, like the commenter on the original post said, you could create a property on your ViewModel that does this.


I'd expose that as a StatusText property on the model.

That kind of logic should really be separate from your UI.

0

精彩评论

暂无评论...
验证码 换一张
取 消