如何仅为特定的MVC操作创建只读文本框?

时间:2016-02-22 10:57:11

标签: asp.net-mvc model-view-controller razor razorengine

标题可能令人困惑,所以这是我的问题: 我想在我的View中只有一个readonly文本框,如果我的Action是用于编辑(比如EditLocation),如果我的Action用于添加新记录(AddLocation),我想要一个可编辑的文本框。

我的ff。代码有效,但我想知道是否有“更清洁”的解决方案

@using (Html.BeginForm(Model.Location.Id == 0 ? "AddLocation" : "EditLocation", "Location"))
    {
        <fieldset>
            @Html.HiddenFor(x => x.Location.Id)
            @Html.HiddenFor(x => x.Location.CompanyGroupId)
            @Html.HiddenFor(x => x.CompanyGroup.Id)
            @Html.HiddenFor(x => x.CompanyGroup.Code)

            <div class="form-group">
                <strong><span>@ResourcesCommon.Location_Code</span></strong>
                @if (Model.Location.Id == 0)
                {
                    @Html.TextBoxFor(x => x.Location.Code, new { @class = "form-control" })
                    @Html.ValidationMessageFor(x => x.Location.Code)
                }
                else
                {
                    @Html.TextBoxFor(x => x.Location.Code, new { @class = "form-control", @readonly = "readonly" })
                    @Html.ValidationMessageFor(x => x.Location.Code)
                }

            </div> ...

谢谢你们,祝他们有一个愉快的一周!

2 个答案:

答案 0 :(得分:2)

这可能会对您有所帮助:

@Html.TextBoxFor(x => x.Location.Code, new Dictionary<string, object>() .AddIf(true, "@class", "form-control") .AddIf(Model.Location.Id != 0, "@readonly", "readonly"))

// This returns the dictionary so that you can "fluently" add values
    public static IDictionary<TKey, TValue> AddIf<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, bool addIt, TKey key, TValue value)
    {
        if (addIt)
            dictionary.Add(key, value);
        return dictionary;
    }

我是从另一个我没有链接的stackoverflow帖子中取出来的。

答案 1 :(得分:0)

你可以这样做(但会产生更多代码):

@Html.TextBoxFor(x => x.Location.Code, new { @class = "form-control", @id="myInput" })

然后添加一些js:

$(document).ready(function() {
    $('#myInput').attr('readonly', @Html.Raw(Model.Location.Id != 0? "true" : "false"));
});