【发布时间】:2018-10-10 10:21:27
【问题描述】:
我目前正在 MVC (c#) 中制作向导。但是我的向导视图中有一个 if 语句,如下所示:
if (Model.Wizard.ClientDetails.GetStep() == Model.Wizard.CurrentStep)
{
@Html.PartialFor(x => x.Wizard.ClientDetails, "_Step");
}
else if (Model.Wizard.Preferences.GetStep() == Model.Wizard.CurrentStep)
{
@Html.PartialFor(x => x.Wizard.ClientPreferences, "_Step")
}
else if (Model.Wizard.ClientQuestions.GetStep() == Model.Wizard.CurrentStep)
{
@Html.PartialFor(x => x.Wizard.ClientQuestions, "_Step")
}
除了我选择显示哪个部分的视图的这一部分之外,向导的设置非常通用。从上面的代码可以看出,每个if 都遵循相同的结构。唯一改变的部分是Model.Wizard.**Property** 部分。
我想尝试删除此 if 语句,这样我就不必担心为添加到新向导的每个步骤编写 if 语句。
我想把代码改成这样:
@Html.PartialFor(x => x.ExampleWizardTransaction.GetStepObject(), "_Step");
我目前对GetStepObject方法的尝试如下:
public static T GetStepObject<T>(this IWizardTransaction wizardTransaction)
where T : class, new()
{
var properties = wizardTransaction.GetType().GetProperties()
.Where(x => x.PropertyType.GetCustomAttributes(typeof(StepAttribute), true).Any());
PropertyInfo @object = properties.FirstOrDefault(x => ((StepAttribute)Attribute
.GetCustomAttribute(x.PropertyType, typeof(StepAttribute))).Step == wizardTransaction.CurrentStep);
}
PropertyInfo @object 部件正在正确选择向导中当前步骤的属性信息。我需要能够将 PropertyInfo @object PropertyInfo 作为正确类型及其当前值返回并以某种方式返回。
这可能吗?
编辑#1:
现有的PartialFor 在正常情况下工作。
public static MvcHtmlString PartialFor<TModel, TProperty>(
this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
{
var name = ExpressionHelper.GetExpressionText(expression);
var model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new TemplateInfo { HtmlFieldPrefix = name }
};
return helper.Partial(partialViewName, model, viewData);
}
编辑#2:
值未绑定的原因是var name = ExpressionHelper.GetExpressionText(expression); 部分返回一个空白字符串。如果我将name 变量硬编码为实际属性,则绑定有效。例如:
public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression, string partialViewName)
{
var compiled = expression.Compile();
var result = compiled.Invoke(helper.ViewData.Model);
var name = ExpressionHelper.GetExpressionText(expression);
//Should be ExampleWizardTransaction.ClientDetails for this step but is blank
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new TemplateInfo
{
//HtmlFieldPrefix = name
HtmlFieldPrefix = "ExampleWizardTransaction.ClientDetails"
}
//Hard coded this to ExampleWizardTransaction.ClientDetails and the bindings now work
};
return helper.Partial(partialViewName, result, viewData);
}
看来我需要能够将向导对象的名称和当前步骤对象作为字符串值传递给TemplateInfo。
【问题讨论】:
-
您能否提供更多关于您的课程结构的信息?在不知道课程结构的情况下询问有关课程反射的问题有点困难。
标签: c# asp.net-mvc generics asp.net-mvc-partialview