programing tip

ASP.NET MVC3 Razor에서 읽기 전용 텍스트 상자를 만드는 방법

itbloger 2020. 8. 3. 08:43
반응형

ASP.NET MVC3 Razor에서 읽기 전용 텍스트 상자를 만드는 방법


Razor보기 엔진을 사용하여 ASP.NET MVC3에서 읽기 전용 텍스트 상자를 작성하는 방법

그렇게 할 수있는 HTMLHelper 메소드가 있습니까?

다음과 같은 것?

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

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

이를 위해 HTML 헬퍼를 만들 수는 있지만 다른 HTML 속성 일뿐입니다. 다른 속성이있는 텍스트 상자에 HTML 도우미를 만드시겠습니까?


업데이트 : 이제 기본 편집기 템플릿에 HTML 속성을 추가하는 것이 매우 간단합니다. 이것을하는 대신에 필요합니다.

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

당신은 단순히 이것을 할 수 있습니다 :

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

이점 : .TextBoxFor템플릿 등 을 호출하지 않아도됩니다 . 전화 .EditorFor하세요.


@Shark의 솔루션이 올바르게 작동하고 간단하고 유용하지만 내 솔루션 (항상 사용하는)은 다음과 같습니다. 속성 을 처리 할 수 있는 생성하십시오editor-templatereadonly :

  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.

예를 들어

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

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

이제 Razor의 기본 구문을 간단하게 사용할 수 있습니다.

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

첫 번째 text-box는 다음과 같이 법선을 렌더링합니다 .

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

두 번째는

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

당신은 모든 유형의 데이터에 대해이 솔루션을 사용할 수 있습니다 ( DateTime, DateTimeOffset, DataType.Text, DataType.MultilineText등). 을 만드십시오 editor-template.


TextBoxFor가있는 솔루션은 괜찮지 만 EditBox stylish와 같은 필드를보고 싶지 않으면 (사용자에게는 약간 혼란 스러울 수 있음) 다음과 같은 변경 사항이 포함됩니다.

  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>
    

일반적으로이 솔루션은 편집에 대해 제출을 비활성화하지만 그 가치를 보여줍니다. 코드 숨김 수정이 필요하지 않습니다.


@Bronek 및 @Shimmy의 이전 답변에 대한 크레딧으로 :

이것은 ASP.NET Core에서 동일한 작업을 수행 한 것과 같습니다.

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

첫 번째 입력은 읽기 전용이며 두 번째 입력은 값을 컨트롤러에 전달하고 숨겨집니다. ASP.NET Core를 사용하는 사람에게 도움이되기를 바랍니다.


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

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

이것은 텍스트 상자에 적합합니다. 그러나 동일한 작업을 수행 checkbox하려고 시도하는 경우 사용하십시오.

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

But don't use disable, because disable always sends the default value false to the server - either it was in the checked or unchecked state. And the readonly does not work for checkbox and radio button. readonly only works for text fields.


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

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"}})

참고URL : https://stackoverflow.com/questions/8761647/how-to-create-a-readonly-textbox-in-asp-net-mvc3-razor

반응형