1

Attempting to make templates out of common scenarios in a UI in MVC and not able to arrive at a solution.

currently a simplified version of the code looks like the following

View model

public class Users
{
   [Display(Name = "FirstName", ResourceType = typeof(ModelResources))]
   public string FirstName { get; set; }

   [Display(Name = "LastName", ResourceType = typeof(ModelResources))]
   public string LastName { get; set; }
}

Partial razor view (_TextInputPartial.chtml)

@model object
 <div class="wrapper">
        <div class="label-wrap">
            @Html.LabelFor(m => m)
        </div>
        <div class="input-wrap">
            @Html.TextBoxFor(m => m)
        </div>
        <div class="validation-wrap">@Html.ValidationMessageFor(m => m)</div>
    </div>

Html extension method for rendering the partial

 public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        string name = ExpressionHelper.GetExpressionText(expression);
        object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
        var viewData = new ViewDataDictionary(helper.ViewData)
        {
            TemplateInfo = new System.Web.Mvc.TemplateInfo
            {
                HtmlFieldPrefix = name
            }
        };

        return helper.Partial("~/Areas/Shared/_TextInputPartial.cshtml", model, viewData);
    }

Usage in the parent view

@using (Html.BeginForm())
{
    Html.PartialFor(m => m.FirstName);
    <br />
    <input type="submit" value="Submit" />
}

Currently this contraption doesn't render anything, when stepping through the code it appears that the partial view gets a value but looses all metadata about the property. What am i doing wrong here? Or is there a better way of doing this?

Ahsan
  • 2,488
  • 2
  • 22
  • 44
  • Difficult to understand what your trying to achieve. Why would you have a partial for a single property. Is your intention to generate a label, textbox and validation message placeholder for a property in a single line of code - (say) `@Html.FieldFor(m => m.FirstName)` –  Jun 20 '15 at 05:01
  • @StephenMuecke Exactly (the reason is i can keep the html centralized so that later if i decided to tweak things i can do it one place) – Ahsan Jun 20 '15 at 05:02
  • [Refer this answer](http://stackoverflow.com/questions/26955073/converting-asp-net-mvc-razor-helper-function-into-a-method-of-a-helper-class/26955246#26955246) –  Jun 20 '15 at 05:04
  • In other words what you are saying is not to use a partial but build the html on the fly? interesting solution. – Ahsan Jun 20 '15 at 05:08

0 Answers0