我有两个用于创建所有者或服务公司的视图,每个视图都有自己的表。
当用户使用标准的View-> Account-> Register视图注册时,我添加了一个单选按钮,询问他们是所有者还是服务公司。我想要实现的是基于哪一个他们选择创建视图的局部视图,他们选择使用单个提交按钮显示选项,该按钮既注册用户又创建所有者或服务公司记录。
查看各种教程我只能找到创建部分视图的MVC 4指南,其中“添加视图”对话框看起来不同。我已经阅读了Professional ASP.NET MVC 5中的部分视图部分,它建议您只使用Retuns PartialView()方法调用视图,但我不确定如何在控制器之外执行此操作并基于用户操作(即选择单选按钮)。
感谢任何建议!
答案 0 :(得分:2)
我建议发布到Register方法,并根据所选选项的值,重定向到相关视图以完成详细信息。用户表可以有(例如)IsRegistrationComplete
字段,仅当第二个表单已保存时才会标记为true
。
要在一个视图中执行此操作,您需要一个包含Register
模型,Owner
模型,ServiceCompany
模型和所选选项属性的视图模型。
查看模型
public class RegistrationVM
{
public RegisterVM Register { get; set; }
public OwnerVM Owner { get; set; }
public ServiceCompanyVM ServiceCompany { get; set; }
[Required]
public string CompanyType { get; set; }
}
控制器
public ActionResult Register()
{
RegistrationVM model = new RegistrationVM();
model.Register = new RegisterVM();
return View(model);
}
public ActionResult Register(RegistrationVM model)
{
// Either Owner or ServiceCompany properties will be populated
}
public PartialViewResult CreateOwner()
{
var model = new RegistrationVM();
model.Owner = new OwnerVM();
return PartialView(model);
}
public PartialViewResult CreateServiceCompany()
{
var model = new RegistrationVM();
model.ServiceCompany = new ServiceCompany();
return PartialView(model);
}
注意:部分视图不应包含<form>
元素(它将插入主视图的<form>
标记内)。部分视图中的模型需要为RegistrationVM
,因此控件正确加上前缀,并且可以在回发后绑定(例如<input name="Owner.SomeProperty" ../>
等)
查看
@model RegistrationVM
@using(Html.BeginForm())
{
<section>
// render controls for the register model
<section>
<section>
@Html.RadioButtonFor(m => m.CompanyType, "owner",new { id = "owner" })
<label for="owner">Owner</label>
@Html.RadioButtonFor(m => m.CompanyType, "service",new { id = "service" })
<label for="service">Service Company</label>
@Html.ValidationMessageFor(m => m.CompanyType)
<button id="next" type="button">Next</button>
<section>
<section id="step2"></section>
<input id="submit" type="submit" /> // style this as hidden
}
然后添加一个脚本来处理Next
按钮,该按钮验证现有控件,获取所选服务的值,使用ajax加载相关表单,重新解析验证器并显示提交按钮
var form = $('form');
$('#next').click(function() {
// Validate what been entered so far
form.validate();
if (!form.valid()) {
return; // correct errors before proceeding
}
// Get selected type and update DOM
var type = $('input[name="CompanyType"]:checked').val();
if (type == "owner") {
$('#step2').load('@Url.Action("CreateOwner")');
} else {
$('#step2').load('@Url.Action("CreateServiceCompany")');
}
// Re-parse validator so client side validation can be applied to the new controls
form.data('validator', null);
$.validator.unobtrusive.parse(form);
// Show submit button
$('#submit').show();
});