REFACTOR HTML.LABELFOR, EDITORFOR, VALIDATIONMESSAGEFOR INTO PARTIAL VIEW

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
 2845  View(s)
Ratings:
Rate this:

Hi Everyone!

I want to refactor view form code to avoid copyPaste. But it's not working. Razor don't allow to write

@model System.Linq.Expressions.Expression<Func<TModel, TValue>> expression
and

@Html.Partial("Item", model => model.EmpName)
Old code, that working:

        <tr>
            <td class="editor-label" style="border: 0;">
                @Html.LabelFor(model=>model.EmpName)
            </td>
            <td class="editor-field" style="border: 0">
                @Html.EditorFor(model=>model.EmpName)
                @Html.ValidationMessageFor(model=>model.EmpName)
            </td>
        </tr>
        <tr>
            <td class="editor-label" style="border: 0;">
                @Html.LabelFor(model=>model.Email)
            </td>
            <td class="editor-field" style="border: 0;">
                @Html.EditorFor(model=>model.Email)
                @Html.ValidationMessageFor(model=>model.Email)
            </td>
        </tr>
After refactoring not working:

Item.cshtml:

   @model System.Linq.Expressions.Expression<Func<TModel, TValue>> expression
        <tr>
            <td class="editor-label" style="border: 0;">
                @Html.LabelFor(expression)
            </td>
            <td class="editor-field" style="border: 0">
                @Html.EditorFor(expression)
                @Html.ValidationMessageFor(expression)
            </td>
        </tr>
    }
New code:

 @Html.Partial("Item", model => model.EmpName)
 @Html.Partial("Item", model => model.Email)

How to make it work?

Thanks in advance

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: refactor Html.LabelFor, EditorFor, ValidationMessageFor into partial view

    Hi Manoj Bhatt!

    You can try this way

    @Html.MyEditFor(m => m.Name)

    Partial view not support lambda express, so you try this way

    @Html.Partial("Item", Model.EmpName)

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!