从通用EditorFor模板绑定我模型的属性值

时间:2018-10-09 11:01:44

标签: c# asp.net-mvc

我正在尝试编写一个通用框架来协助开发向导样式的表单。

我有一个模型,该模型的属性表示向导中的每个步骤,例如

public class ExampleWizardTransaction : WizardTransaction
{
    public override TransactionType TransactionType { get; set; } = TransactionType.ExampleWizard;
    public override string ControllerName { get; set; } = "WizardExample";

    [DisplayName("Client Details")]
    public ClientDetails ClientDetails { get; set; } = new ClientDetails();

    [DisplayName("Client Questions")]
    public ClientQuestions ClientQuestions { get; set; } = new ClientQuestions();

    [DisplayName("Client Preferences")]
    public ClientPreferences ClientPreferences { get; set; } = new ClientPreferences();
}

[Step(1)]
public class ClientDetails : IStep
{
    [Display(Description = "Please enter your first name")]
    public string FirstName { get; set; }

    [Display(Description = "Please enter your last name")]
    public string LastName { get; set; }
}

[Step(2)]
public class ClientQuestions : IStep
{
    [DisplayName("What is your favourite car?")]
    public string FavouriteCar { get; set; }

    [DisplayName("What is your favourite holiday destination?")]
    public string FavouriteDestination { get; set; }
}

[Step(3)]
public class ClientPreferences : IStep
{
    [DisplayName("Red or Blue?")]
    public Colours Colour { get; set; }

    [DisplayName("Do you like Indian food")]
    public bool LikeFood { get; set; }
}

最初,我对每个向导步骤都有部分视图,如下所示:

@model Web.Models.ExampleWizard.Create

<div class="row">
    <div class="col-md-6">
        @Html.EditorFor(x => x.ExampleWizardTransaction.ClientDetails)
    </div>
</div>

使用此方法,我的表单的值可以正确绑定,因为当我将其发布时,MVC知道绑定上下文。

在我的表单上,我通过传递步骤号(例如,

Html.RenderPartial($"_CreateWizard_{Model.ExampleWizardTransaction.CurrentStep}", Model);

我正在尝试对代码进行一般化,因此不需要在向导的每个步骤中都包含部分视图。

为此,我呈现了一个操作,该操作确定与向导步骤相关联的类型,然后返回部分视图:

Html.RenderAction("GetStep", "ExampleWizard", Model.ExampleWizardTransaction);

我的局部视图指定每个向导步骤实现的接口:

_WizardStep.cshtml

@model Services.ViewModels.Wizard.IStep

<div class="row">
    <div class="col-md-6">
        @Html.EditorFor(x => x)
    </div>
</div>

当我使用上面的方法时,表单可以正确显示,但是值不再绑定在POST上,我认为这是因为它没有属性的绑定上下文(例如,输入的ID和名称)类型不完全合格)。

我在向导步骤中具有用于字符串属性的EditorFor模板,该模板呈现文本框:

@model string
<div class="col-md-12">
    <div class="form-group">
        <label class="m-b-none" for="@ViewData.Model">
            @ViewData.ModelMetadata.DisplayName
        </label>
        <span class="help-block m-b-none small m-t-none">@ViewData.ModelMetadata.Description</span>
        <div class="input-group">
            @Html.TextBox("", Model, new {@class = "form-control"})
            <div class="input-group-addon">
                <i class="fa validation"></i>
            </div>
        </div>

    </div>
</div>

是否可以使用通用的“ _WizardStep.cshtml”局部视图,并将当前步骤的属性仍绑定到模型中?

我的控制器如下:

[HttpPost]
public virtual ActionResult CreateWizard(Create model, string action)
{
    var createModel = CreateModel<Create>();
    switch (createModel.Save(action))
    {
        case WizardState.Finished:
            return RedirectToActionWithMessage("List", "Transaction", "Completed", ToastNotificationStatus.Success);
        case WizardState.Ongoing:
            return RedirectToAction(MVC.ExampleWizard.CreateWizard(
                model.ExampleWizardTransaction.Id,
                model.ExampleWizardTransaction.GetNextStep(action)));
        default:
            model.MapExistingTransactions<ExampleWizardTransaction>();
            return View(model);
    }
}

我的“创建”模型包含我的“ ExampleWizardTransaction”属性,该属性包含实现IStep接口的每个向导步骤。

1 个答案:

答案 0 :(得分:1)

从@StephenMuecke的答案中汲取灵感,我采用了以下方法。

在“ CreateWizard.cshtml”视图上,使用以下行呈现该步骤:

@Html.WizardPartialFor(x => x.ExampleWizardTransaction.GetStepObject<IStep>(), "_WizardStep", Model.ExampleWizardTransaction)

这将调用'WizardPartialFor'扩展方法:

public static MvcHtmlString WizardPartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
    Expression<Func<TModel, TProperty>> expression, string partialViewName, IWizardTransaction wizardTransaction)
{
    var compiled = expression.Compile();
    var result = compiled.Invoke(helper.ViewData.Model);

    PropertyInfo currentStep = wizardTransaction.GetCurrentStepPropertyInfo();

    string currentStepName = currentStep.PropertyType.Name;

    var name = $"{currentStep.DeclaringType.Name}.{currentStepName}";

    var viewData = new ViewDataDictionary(helper.ViewData)
    {
        TemplateInfo = new TemplateInfo { HtmlFieldPrefix = name }
    };

    return helper.Partial(partialViewName, result, viewData);
}

public static PropertyInfo GetCurrentStepPropertyInfo(this IWizardTransaction wizardTransaction)
{
    var properties = wizardTransaction.GetType().GetProperties()
        .Where(x => x.PropertyType.GetCustomAttributes(typeof(StepAttribute), true).Any());

    return properties.FirstOrDefault(x => ((StepAttribute)Attribute
        .GetCustomAttribute(x.PropertyType, typeof(StepAttribute))).Step == wizardTransaction.CurrentStep);
}

在此扩展方法中,我们调用一个扩展方法,该方法获取向导步骤对象:

public static TProperty GetStepObject<TProperty>(this IWizardTransaction wizardTransaction)
    where TProperty : class
{
    var properties = wizardTransaction.GetType().GetProperties()
        .Where(x => x.PropertyType.GetCustomAttributes(typeof(StepAttribute), true).Any());

    var @object = properties.FirstOrDefault(x => ((StepAttribute)Attribute
            .GetCustomAttribute(x.PropertyType, typeof(StepAttribute))).Step == wizardTransaction.CurrentStep);

    return @object.GetValue(wizardTransaction) as TProperty;
}

这成功呈现了我的通用_WizardStep部分视图,并且还成功地在POST上绑定了数据。