在MVC5应用程序中注册期间获取其他信息

时间:2017-11-09 22:48:45

标签: c# jquery entity-framework asp.net-mvc-5 asp.net-identity

将MVC5应用程序放在一起,我想要做的是让用户注册为客户端或商人。登录详细信息可以进入创建的相同默认[AspNetUsers]表,但如果他们是商人,我希望收集其他详细信息。当我查看应用程序附带的一些代码时,我对于接下来应该做什么或者即使我使用的方法是正确的而感到有些困惑。我的目的是根据填写的信息收集任何一组注册信息。

我的帐户/注册控制器开始如下:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        using (var context = new ApplicationDbContext())
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    UserName = model.Email,
                    Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);                    

                if (result.Succeeded)
                {
                    if (model.CompanyName.Trim().Length > 0)
                    {
                        var company = new CompanyModel
                        {
                            CompanyName = model.CompanyName,
                            AddressLine1 = model.AddressLine1,
                            AddressLine2 = model.AddressLine2,
                            Town = model.Town,
                            County = model.County,
                            Postcode = model.Postcode,
                            TelNo = model.TelNo,
                            MobNo = model.MobNo,
                            GoogleVerified = model.GoogleVerified,
                            FacebookProfileUrl = model.FacebookProfileUrl
                        };

                        //insert company details?
                    }                        

                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }

所以我的问题是我做的正确/好事,我可以通过同一个控制器收集两类用户的详细信息。

同样在Register.cshtml页面我有一个jquery手风琴,作为客户的想法可以填写一个部分并加入或者商人可以点击手风琴,它会显示另一个要填写的部分。我接下来的问题是我曾经使用过这行代码:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))

{

然后将手风琴控制放在其中,这意味着我有这些控件

@Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })

两次,一次是针对用户,一次针对一位商人,这是允许的吗?

1 个答案:

答案 0 :(得分:2)

添加<label>两次很好,但我认为你必须将关联的@Html.TextBoxFor(m => m.FirstName)重复,这不是很好,因为(1)它会生成重复的id属性是无效的html和(2)DefaultModelBinder只会在第一个输入name="FirstName"时绑定值。

没有理由重复控制。而是使用条件验证属性(例如foolproof CompanyModel)修饰与[RequiredIf]关联的视图模型属性,以便在用户也是商人时需要它们。由于您已指明用户可以是商人,因此我建议使用bool属性来生成复选框。您的视图模型看起来像

public class RegisterViewModel
{
    // Properties associated with ApplicationUser
    [Display(Name = "Company Name")]
    [Required(ErrorMessage = "Please enter your First Name")]
    public string FirstName { get; set; }
    ....
    public bool IsTradesPerson { get; set; }
    // Properties associated with CompanyModel
    [Display(Name = "Company Name")]
    [RequiredIfTrue("IsTradesPerson", ErrorMessage = "Please enter your Company Name")]
    public string CompanyName { get; set; }
    ....
}

并在视图中,将与CompanyModel模型关联的控件放在隐藏的<div>元素中,以便根据IsTradesPerson属性

切换其可见性
<div id="usercontrols">
    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)
    @Html.ValidationMessageFor(m => m.FirstName)
    ....
    @Html.LabelFor(m => m.IsTradesperson)
    @Html.CheckBoxFor(m.IsTradesperson)
</div>
<div id="tradespersoncontrols" hidden>
    @Html.LabelFor(m => m.CompanyName)
    @Html.TextBoxFor(m => m.CompanyName)
    @Html.ValidationMessageFor(m => m.CompanyName)
    ....
<div>

以及切换可见性的脚本

var controls = $('tradespersoncontrols');
$('#IsTradesperson').click(function) {
    if ($(this).is(':checked')) {
        controls.show();
    } else {
        controls.hide();
    }
});

然后在POST方法中,您可以检查if(model.IsTradesperson),如果是,请根据视图模型属性创建CompanyModel并保存。