开发者

MVC : Set disabled or no for a textbox in HTMLAttribute

开发者 https://www.devze.com 2023-02-21 18:55 出处:网络
In my HTML file, I have a textbox which must be disabled or enable, depending on my controller value.

In my HTML file, I have a textbox which must be disabled or enable, depending on my controller value. No problem to set it in disabled mode, but to set it enable...

this is my code :

<%= Html.TextBoxFor开发者_Python百科(model => model.test, new Dictionary<string, object> { { "disabled", ViewContext.RouteData.Values["controller"].ToString() == "MyTest" ? "" : "disabled"}}

I have seen some ideas on this question : here

mvccontrib.FluentHtml or InputExtensions are the single solutions, to answer to my question ???

Im using "disabled" but I can use "read-only" attribute... the goal of this code is not to allow the user to fill the text box...

Thanks for your advices on the subject.


Just break the line apart into something like this:

<% 
if (MyConditionIsTrue) 
    Response.Write(Html.TextBoxFor(model => model.test, new { disabled = "true" }));
else 
    Response.Write(Html.TextBoxFor(model => model.test));
%>


That's a good candidate for a custom HTML helper:

public static class HtmlExtensions
{
    public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex)
    {
        var controller = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
        var htmlAttributes = new Dictionary<string, object>();
        if (string.Equals(controller, "MyTest", StringComparison.OrdinalIgnoreCase))
        {
            htmlAttributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(ex, htmlAttributes);
    }
}

and then:

<%= Html.CustomTextBoxFor(model => model.test) %>


People love Html helpers, but you don't have to use them.

@if (MyConditionIsTrue) {
  <input id="test" name="test" value="@Model.test" disabled="disabled" />
}
else {
  <input id="test" name="test" value="@Model.test" />
}

If you have to reuse this logic many times, a html helper is probably a good idea. If you're just doing it once, it might not be.


disabled
or
disabled = disabled
or
disabled = true
or
disabled = false
or
disabled = enable

all of the above means disabled.

remove disabled from the element to enable that.

if(condition)
   <input .... disabled/>
else
   <input ..... />
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号