ProgramingTip

Html.TextBoxFor에 대한 조건에 따라 속성 설정

bestdevel 2020. 10. 20. 07:56
반응형

Html.TextBoxFor에 대한 조건에 따라 속성 설정


asp.net MVC에서 Html.TextBoxFor에 대한 조건에 따라 속성을 설정하고 싶습니다.

@Html.TextBoxFor(model => model.ExpireDate, new { style = "width: 70px;", maxlength = "10", id = "expire-date" disabled = (Model.ExpireDate == null ? "disable" : "") })

이 도우미는 두 개의 중재 됨 = "disabled"또는 ""입니다. 두 테마 모두 텍스트 상자를 선택합니다.

Model.ExpireDate == null이면 텍스트 상자를 선택하고 싶습니다. 확장되어 활성화하고 싶습니다.


유효한 방법은 다음과 가능합니다.

disabled="disabled"

브라우저도 받아 들일 수 disabled="" 있습니다. 첫 번째 접근 방식을 권장합니다.

이제 가능한 코드 조각으로 캡슐화하기 위해 사용자 정의 HTML 도우미를 작성하는 것이 좋습니다.

using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression, 
        object htmlAttributes, 
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
}

다음과 같이 사용할 수 있습니다.

@Html.MyTextBoxFor(
    model => model.ExpireDate, 
    new { 
        style = "width: 70px;", 
        maxlength = "10", 
        id = "expire-date" 
    }, 
    Model.ExpireDate == null
)

도우미에이 더 많은 지능가져올 수 있습니다 .

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        object htmlAttributes
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        if (metaData.Model == null)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
}

이제 더 이상 필요가 없습니다.

@Html.MyTextBoxFor(
    model => model.ExpireDate, 
    new { 
        style = "width: 70px;", 
        maxlength = "10", 
        id = "expire-date" 
    }
)

실제로 내부 동작은 익명 객체를 사전으로 변환합니다. 그래서이 시나리오에서 제가하는 일 사전을 찾는 것입니다.

@{
  var htmlAttributes = new Dictionary<string, object>
  {
    { "class" , "form-control"},
    { "placeholder", "Why?" }        
  };
  if (Model.IsDisabled)
  {
    htmlAttributes.Add("disabled", "disabled");
  }
}
@Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })

또는 Stephen이 여기에서 언급 했듯이 :

@Html.EditorFor(m => m.Description,
    Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })

나는 Darin 방법을 좋아합니다. 하지만이 문제를 빠르게 해결하는 방법은

Html.TextBox("Expiry", null, new { style = "width: 70px;", maxlength = "10", id = "expire-date", disabled = "disabled" }).ToString().Replace("disabled=\"disabled\"", (1 == 2 ? "" : "disabled=\"disabled\""))

일부 확장 방법을 사용하여 달성했습니다.

private const string endFieldPattern = "^(.*?)>";

    public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
    {
        string rawString = htmlString.ToString();
        if (disabled)
        {
            rawString = Regex.Replace(rawString, endFieldPattern, "$1 disabled=\"disabled\">");
        }

        return new MvcHtmlString(rawString);
    }

    public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
    {
        string rawString = htmlString.ToString();
        if (@readonly)
        {
            rawString = Regex.Replace(rawString, endFieldPattern, "$1 readonly=\"readonly\">");
        }

        return new MvcHtmlString(rawString);
    }

그리고 ....

@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsDisabled(Model.ExpireDate == null)

내가 해결 한 가지 간단한 접근 방식은 조건부 방식입니다.

@(Model.ExpireDate == null ? 
  @Html.TextBoxFor(m => m.ExpireDate, new { @disabled = "disabled" }) : 
  @Html.TextBoxFor(m => m.ExpireDate)
)

html 도우미를 사용하지 않는 경우 다음과 같은 간단한 삼항 사용 가능합니다.

<input name="Field"
       value="@Model.Field" tabindex="0"
       @(Model.IsDisabledField ? "disabled=\"disabled\"" : "")>

이것은 늦었지만 어떤 사람들에게 도움이 될 수 있습니다.

@DarinDimitrov의 답변을 확장하여 disabled="disabled" checked="checked", selected="selected"의 부울 html 속성을 취하는 두 번째 개체를 사용할 수 있습니다 .

속성 값이 true 인 경우에는 오류가없는 언어 항목과 속성은 언어 적이 지 않습니다.

사용자 정의 재사용 가능한 HtmlHelper :

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
                                                                Expression<Func<TModel, TProperty>> expression,
                                                                object htmlAttributes,
                                                                object booleanHtmlAttributes)
    {
        var attributes = new RouteValueDictionary(htmlAttributes);

        //Reflect over the properties of the newly added booleanHtmlAttributes object
        foreach (var prop in booleanHtmlAttributes.GetType().GetProperties())
        {
            //Find only the properties that are true and inject into the main attributes.
            //and discard the rest.
            if (ValueIsTrue(prop.GetValue(booleanHtmlAttributes, null)))
            {
                attributes[prop.Name] = prop.Name;
            }                
        }                                

        return htmlHelper.TextBoxFor(expression, attributes);
    }

    private static bool ValueIsTrue(object obj)
    {
        bool res = false;
        try
        {
            res = Convert.ToBoolean(obj);
        }
        catch (FormatException)
        {
            res = false;
        }
        catch(InvalidCastException)
        {
            res = false;
        }
        return res;
    }

}

다음과 같이 사용할 수 있습니다.

@Html.MyTextBoxFor(m => Model.Employee.Name
                   , new { @class = "x-large" , placeholder = "Type something…" }
                   , new { disabled = true})

RouteValueDictionary (IDictionary를 기반으로하므로 htmlAttributes로 잘 작동 함) 및 확장 메서드를 사용하여 해결됩니다.

public static RouteValueDictionary AddIf(this RouteValueDictionary dict, bool condition, string name, object value)
{
    if (condition) dict.Add(name, value);
    return dict;
}

용법:

@Html.TextBoxFor(m => m.GovId, new RouteValueDictionary(new { @class = "form-control" })
.AddIf(Model.IsEntityFieldsLocked, "disabled", "disabled"))

크레딧은 https://stackoverflow.com/a/3481969/40939이동합니다.


Html Helpers를 사용하고 싶지 않다면 내 솔루션을 살펴보십시오.

disabled="@(your Expression that returns true or false")"

그것은 그

@{
    bool isManager = (Session["User"] as User).IsManager;
}
<textarea rows="4" name="LetterManagerNotes" disabled="@(!isManager)"></textarea>

더 좋은 방법은 컨트롤러에서 확인을 수행하고 뷰 (Razor 엔진) 내에서 액세스 할 수있는 변수 내에 저장하여 the view free from business logic


또 다른 해결책은 Dictionary<string, object>호출하기 전에을 만들고 TextBoxFor해당 사전을 전달하는 것입니다. 사전 "disabled"에서 텍스트 상자가 비활성화되는 경우에만 키를 추가하십시오 . 가장 깔끔한 솔루션은 아니지만 간단하고 간단합니다.


또 다른 방법은 클라이언트 측에서 텍스트 상자를 비활성화하는 것입니다.

귀하의 경우 비활성화해야 할 텍스트 상자가 하나만 있지만 비활성화 할 필요가없는 여러 입력, 선택 및 텍스트 영역 필드가있는 경우를 고려하십시오.

jquery + (클라이언트에서 오는 데이터에 의존 할 수 없기 때문에)를 통해 수행하는 것이 훨씬 쉽습니다. 이러한 필드가 저장되지 않도록 컨트롤러에 로직을 추가합니다.

다음은 그 예입니다.

<input id="document_Status" name="document.Status" type="hidden" value="2" />

$(document).ready(function () {

    disableAll();
}

function disableAll() {
  var status = $('#document_Status').val();

  if (status != 0) {
      $("input").attr('disabled', true);
      $("textarea").attr('disabled', true);
      $("select").attr('disabled', true);
  }
}

참고 URL : https://stackoverflow.com/questions/6660146/set-disable-attribute-based-on-a-condition-for-html-textboxfor

반응형