【发布时间】:2015-07-31 10:50:31
【问题描述】:
我找到了如何在 ASP MVC 中创建向导的绝佳答案。
multi-step registration process issues in asp.net mvc (splitted viewmodels, single model)
我只有一个与此相关的问题。将数据填充到视图模型中的最佳做法是什么?
假设在第 2 步中,我需要向用户显示数据列表。列表数据来自数据库。然后我会继续为视图模型创建一个构造函数,还是应该将它填充到控制器中?
这就是我的代码现在的样子。
型号
[Serializable]
public class Step1ViewModel : IStepViewModel
{
public bool MyProperty { get; set; }
}
[Serializable]
public class Step2ViewModel : IStepViewModel
{
// This needs to be populated with data, I need to display it in a list
public List<string> MyList { get; set; }
}
[Serializable]
public class Step3ViewModel : IStepViewModel
{
public bool MyProperty { get; set; }
}
[Serializable]
public class PublishViewModel
{
public int CurrentStepIndex { get; set; }
public IList<IStepViewModel> Steps { get; set; }
public void Initialize()
{
Steps = typeof(IStepViewModel)
.Assembly
.GetTypes()
.Where(t => !t.IsAbstract && typeof(IStepViewModel).IsAssignableFrom(t))
.Select(t => (IStepViewModel)Activator.CreateInstance(t))
.ToList();
}
public class PublishViewModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var stepTypeValue = bindingContext.ValueProvider.GetValue("StepType");
var stepType = Type.GetType((string)stepTypeValue.ConvertTo(typeof(string)), true);
var step = Activator.CreateInstance(stepType);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => step, stepType);
return step;
}
}
public interface IStepViewModel
{
}
控制器
public ActionResult Publish(int? id)
{
var publish = new PublishViewModel();
publish.Initialize();
return View(publish);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Publish([Deserialize] PublishViewModel publish, IStepViewModel step)
{
publish.Steps[publish.CurrentStepIndex] = step;
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(Request["next"]))
{
publish.CurrentStepIndex++;
}
else if (!string.IsNullOrEmpty(Request["prev"]))
{
publish.CurrentStepIndex--;
}
else
{
// TODO: we have finished: all the step partial
// view models have passed validation => map them
// back to the domain model and do some processing with
// the results
return Content("thanks for filling this form", "text/plain");
}
}
else if (!string.IsNullOrEmpty(Request["prev"]))
{
// Even if validation failed we allow the user to
// navigate to previous steps
publish.CurrentStepIndex--;
}
return View(publish);
}
所以我的问题是,我应该在哪里填充 Step2 的列表? 我的第一个想法是在 Step2 视图模型中有一个构造函数。第二个想法是在控制器中有一些逻辑找出我在哪一步,并从那里填充它。但这听起来有点糟糕。
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-mvc-4