如果文本框有值,如何设置只读?

时间:2012-11-06 01:52:43

标签: c# asp.net-mvc

如果文本框在MVC中具有视图值,我想将其设置为只读。

所以我写了

 <tr>
 @if (model.first_name != "" ) { 
   <td >
                @Html.LabelFor(model => model.first_name):
            </td>
            <td >
                @Html.TextBoxFor(model => model.first_name)
                <span class="required">*</span>
                @Html.ValidationMessageFor(model => model.first_name)
            </td>
@ else  
  <td >
  @Html.LabelFor(model => model.first_name):
            </td>
            <td >
                @Html.EditorFor(model => model.first_name)
                <span class="required">*</span>
                @Html.ValidationMessageFor(model => model.first_name)
            </td>
@}

            <td >
                @Html.LabelFor(model => model.first_name):
            </td>
            <td >
                @Html.EditorFor(model => model.first_name)
                <span class="required">*</span>
                @Html.ValidationMessageFor(model => model.first_name)
            </td>
        </tr>

但是不起作用.. 如何解决? 我该怎么办?

3 个答案:

答案 0 :(得分:3)

您可以设置字段readonly="readonly"而不是disabled="disabled"只读字段值将提交给服务器,同时仍然是用户无法编辑的。

答案 1 :(得分:3)

您可以修改视图模型,如下所示

public class MyViewModel
{
  public string first_name { get; set; }

  public object first_name_attributes
  {
    get
    {
      return string.IsNullOrEmpty(first_name) ? null : new { @readonly = "readonly" };
    }
  }
}

在您的UI中,您可以以声明方式添加对象。

Html.TextBoxFor(x => x.first_name, first_name_attributes)

这样可以实现更简单的UI,并且视图模型具有可单元测试的优势!

答案 2 :(得分:1)

在razor中创建一个if语句,并在要禁用的输入/编辑器上禁用=“disabled”。

@if
(model.first_name != null)
{

   <td >
            @Html.LabelFor(model => model.first_name):
        </td>
        <td >
            @Html.TextBoxFor(model => model.first_name)
            <span class="required">*</span>
            @Html.ValidationMessageFor(model => model.first_name)
        </td>
}
else
{
  <td >
  @Html.LabelFor(model => model.first_name):
        </td>
        <td >
            @Html.EditorFor(model => model.first_name, new { disabled = "disabled", @readonly = "readonly" }))
            <span class="required">*</span>
            @Html.ValidationMessageFor(model => model.first_name)
        </td>

        <td >
            @Html.LabelFor(model => model.first_name):
        </td>
        <td >
            @Html.EditorFor(model => model.first_name)
            <span class="required">*</span>
            @Html.ValidationMessageFor(model => model.first_name)
        </td>
    </tr>

}