C# 如何在 ASP.NET MVC3 Razor 中创建只读文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8761647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:19:34  来源:igfitidea点击:

How to create a readonly textbox in ASP.NET MVC3 Razor

c#asp.net-mvc-3razorhtml-helperreadonly-attribute

提问by Shyju

How do I create a readonly textbox in ASP.NET MVC3 with the Razor view engine?

如何使用 Razor 视图引擎在 ASP.NET MVC3 中创建只读文本框?

Is there an HTMLHelper method available to do that?

是否有可用的 HTMLHelper 方法来做到这一点?

Something like the following?

类似于以下内容?

@Html.ReadOnlyTextBoxFor(m => m.userCode)

采纳答案by Shyju

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?

欢迎您为此创建一个 HTML Helper,但这只是一个 HTML 属性,就像任何其他属性一样。您会为具有其他属性的文本框制作 HTML Helper 吗?

回答by ravy amiry

UPDATE:Now it's very simple to add HTML attributes to the default editor templates. It neans instead of doing this:

更新:现在将 HTML 属性添加到默认编辑器模板非常简单。它 neans 而不是这样做:

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

you simply can do this:

你可以这样做:

@Html.EditorFor(m => m.userCode, new { htmlAttributes = new { @readonly="readonly" } })

Benefits: You haven't to call .TextBoxFor, etc. for templates. Just call .EditorFor.

好处:您不必.TextBoxFor为模板调用等。就打电话.EditorFor



While @Shark's solution works correctly, and it is simple and useful, my solution (that I use always) is this one: Create an editor-templatethat can handles readonlyattribute:

虽然@Shark 的解决方案工作正常,而且简单实用,但我的解决方案(我一直使用)是这样的:创建一个editor-template可以处理readonly属性的解决方案

  1. Create a folder named EditorTemplatesin ~/Views/Shared/
  2. Create a razor PartialViewnamed String.cshtml
  3. Fill the String.cshtmlwith this code:

    @if(ViewData.ModelMetadata.IsReadOnly) {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line readonly", @readonly = "readonly", disabled = "disabled" })
    } else {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line" })
    }
    
  4. In model class, put the [ReadOnly(true)]attribute on properties which you want to be readonly.

  1. 创建一个文件夹命名EditorTemplates~/Views/Shared/
  2. 创建一个PartialView名为的剃刀String.cshtml
  3. 填写String.cshtml以下代码:

    @if(ViewData.ModelMetadata.IsReadOnly) {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line readonly", @readonly = "readonly", disabled = "disabled" })
    } else {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line" })
    }
    
  4. 在模型类中,将[ReadOnly(true)]属性放在您想要的属性上readonly

For example,

例如,

public class Model {
    // [your-annotations-here]
    public string EditablePropertyExample { get; set; }

    // [your-annotations-here]
    [ReadOnly(true)]
    public string ReadOnlyPropertyExample { get; set; }
}

Now you can use Razor's default syntax simply:

现在您可以简单地使用 Razor 的默认语法:

@Html.EditorFor(m => m.EditablePropertyExample)
@Html.EditorFor(m => m.ReadOnlyPropertyExample)

The first one renders a normal text-boxlike this:

第一个渲染这样的法线text-box

<input class="text-box single-line" id="field-id" name="field-name" />

And the second will render to;

第二个将呈现为;

<input readonly="readonly" disabled="disabled" class="text-box single-line readonly" id="field-id" name="field-name" />

You can use this solution for any type of data (DateTime, DateTimeOffset, DataType.Text, DataType.MultilineTextand so on). Just create an editor-template.

您可以使用此解决方案的任何类型的数据(DateTimeDateTimeOffsetDataType.TextDataType.MultilineText等)。只需创建一个editor-template.

回答by Bronek

The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish(it might be a little confusing for the user) involve changes as follows:

使用 TextBoxFor 的解决方案是可以的,但是如果您不想看到像 EditBox 那样时尚的字段(这对用户来说可能有点混乱)涉及如下更改:

  1. Razor code before changes

    <div class="editor-field">
         @Html.EditorFor(model => model.Text)
         @Html.ValidationMessageFor(model => model.Text)
    </div>
    
  2. After changes

    <!-- New div display-field (after div editor-label) -->
    <div class="display-field">
        @Html.DisplayFor(model => model.Text)
    </div>
    
    <div class="editor-field">
        <!-- change to HiddenFor in existing div editor-field -->
        @Html.HiddenFor(model => model.Text)
        @Html.ValidationMessageFor(model => model.Text)
    </div>
    
  1. 更改前的剃刀代码

    <div class="editor-field">
         @Html.EditorFor(model => model.Text)
         @Html.ValidationMessageFor(model => model.Text)
    </div>
    
  2. 更改后

    <!-- New div display-field (after div editor-label) -->
    <div class="display-field">
        @Html.DisplayFor(model => model.Text)
    </div>
    
    <div class="editor-field">
        <!-- change to HiddenFor in existing div editor-field -->
        @Html.HiddenFor(model => model.Text)
        @Html.ValidationMessageFor(model => model.Text)
    </div>
    

Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.

通常,此解决方案会阻止字段编辑,但会显示其值。无需进行代码隐藏修改。

回答by Adithya Baddula

With credits to the previous answer by @Bronek and @Shimmy:

归功于@Bronek 和@Shimmy 之前的回答:

This is like I have done the same thing in ASP.NET Core:

这就像我在 ASP.NET Core 中做了同样的事情:

<input asp-for="DisabledField" disabled="disabled" />
<input asp-for="DisabledField" class="hidden" />

The first input is readonly and the second one passes the value to the controller and is hidden. I hope it will be useful for someone working with ASP.NET Core.

第一个输入是只读的,第二个输入将值传递给控制器​​并隐藏。我希望它对使用 ASP.NET Core 的人有用。

回答by Hossein Dahr

 @Html.TextBox("Receivers", Model, new { @class = "form-control", style = "width: 300px", @readonly = "readonly" })

回答by gdmanandamohon

@Html.TextBoxFor(model => model.IsActive, new { readonly= "readonly" })

This is just fine for text box. However, if you try to do same for the checkboxthen try using this if you are using it:

这对文本框来说很好。但是,如果您尝试checkbox对它做同样的事情,那么如果您正在使用它,请尝试使用它:

@Html.CheckBoxFor(model => model.IsActive, new { onclick = "return false" })

But don't use disable, because disable always sends the default value falseto the server - either it was in the checked or unchecked state. And the readonlydoes not work for checkbox and radio button. readonlyonly works for textfields.

但不要使用disable,因为 disable 总是将默认值发送false到服务器 - 它处于选中或未选中状态。并且readonly不适用于复选框和radio buttonreadonly仅适用于text字段。

回答by Krishan Dutt Sharma

You can use the below code for creating a TextBox as read-only.

您可以使用以下代码将 TextBox 创建为只读。

Method 1

方法一

 @Html.TextBoxFor(model => model.Fields[i].TheField, new { @readonly = true })

Method 2

方法二

@Html.TextBoxFor(model => model.Fields[i].TheField, new { htmlAttributes = new {disabled = "disabled"}})