开发者

How would you create an ASP.NET MVC EditorTemplate that disables field if data is present?

I don't have a lot of experience writing EditorTemplates, the one I've written was to apply a css class to a textarea (I find it odd that the EditorFor method doesn't have an overload for applying HTML attributes).

I'm trying to create a form, that has several fields that - if there is already data present (in the viewdata model) - that those fields would remain in the form, but be disabled so visitors cannot change them... leaving the open fields active to change.

I wish to us开发者_运维问答e the HTML.EditorFor(model => model.property) syntax, is it possible to create an EditorTemplate that does what I described?


Here is an example that should get you started. Inside the editor template you would check if the value of the model is empty or null and if so pass in a custom dictionary of HtmlAttributes to the TextBox or area template.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%
    IDictionary<string, object> htmlAttributes = new Dictionary<string, object>();
    if(!String.IsNullOrWhiteSpace(Model))
    {
        htmlAttributes.Add("disabled", "disabled");
    }
%>
<%: Html.TextBox("Name", Model, htmlAttributes)%>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜