开发者

asp.net mvc razor reuse editor view for display (with custom helper)

开发者 https://www.devze.com 2023-03-31 14:31 出处:网络
I have to make a large amount of forms for a project I\'m working on. Every form has a large amount of fields in them. Would it be possible to create an HTML helper that can display an element or edit

I have to make a large amount of forms for a project I'm working on. Every form has a large amount of fields in them. Would it be possible to create an HTML helper that can display an element or edit element depending on some variable? Maybe someone has tried this already开发者_StackOverflow社区. I could imagine that It would be something like:

@Html.EditOrDisplayFor(m=>m.Field, isReadonly)

When it is readonly it displays only the variable and when it is not it shows an textbox. Beside this helper I need some if's in my views, but it saves a couple of 100 lines of code if this would be possible)


Just found an alternative (I think quite neat way) to do it:

    public static MvcHtmlString EditOrDisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> p,bool readOnly){
        if (readOnly){
            return new MvcHtmlString(string.Format("{0}", html.DisplayFor(p)));
        }  else{
            return new MvcHtmlString(string.Format("{0}", html.EditorFor(p)));
        }

    } 


You can do two things to help you here.

Extension Methods

The first is to write an extension method that allows you to construct an input box with your specifications, e.g:

public static class Extensions
{
    public static string EditOrDisplayFor(this HtmlHelper helper, Field field, bool readOnly)
    {
        StringBuilder builder = new StringBuilder();
        if(readOnly)
        {
            builder.Append(field.Value);
        }
        else
        {
            builder.Append("<input type=\"text\" name=\"")
                   .Append(field.Name)
                   .Append("\" value=\"")
                   .Append(field.Value)
                   .Append("\" />");
        }
        return helper.Raw(builder.ToString());
    }
}

Which you can now use as you have described.

Partial Views

If these forms end up having common groupings between them, you might want to consider putting these common sections in to partial views to cut down on redundant layout code.

0

精彩评论

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