วิธีที่ถูกต้องคือ:
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"
}
)
person
Darin Dimitrov
schedule
12.07.2011