[英]Adding a drop down view of items from another model in the user registration view (ASP.NET MVC5)
I'm creating a system in ASP.NET that allows users to register, choosing (among other things) a cell phone number and a cell carrier. 我正在ASP.NET中创建一个系统,允许用户注册,选择(除其他外)手机号码和手机号码。 I am using Individual User Accounts in the MVC Template using MVC 5. I have another model called "Carriers," that keeps track of all carriers as well as their Email to SMS gateway. 我在使用MVC 5的MVC模板中使用个人用户帐户。我有另一个名为“运营商”的模型,它跟踪所有运营商以及他们的电子邮件到SMS网关。 The model specification is in it's own file, CarrierModels.cs: 模型规范在它自己的文件CarrierModels.cs中:
public class Carrier
{
public string name { get; set; }
public int id { get; set; }
public string gateway { get; set; }
}
I am trying to get a drop-down in the user registration that will let users select from the set of carriers (There is another controller handling creation and modification of carriers). 我试图在用户注册中获得一个下拉菜单,让用户从该组运营商中进行选择(还有另一个控制器处理载体的创建和修改)。 I tried modifying the RegisterViewModel class in AccountViewModels and using LINQ to pull items from a list, but that continuously gives me a Null Reference Exception. 我尝试在AccountViewModels中修改RegisterViewModel类并使用LINQ从列表中提取项目,但这不断给我一个Null Reference Exception。 How should I go about getting this drop down menu into the registration page? 我应该如何将此下拉菜单放入注册页面?
Edit 2: Showing more code (In it's updated form): 编辑2:显示更多代码(以其更新的形式):
Here is the View Code overall, the DropDownListFor line is what causes NullReferenceExceptions. 这是整体的视图代码,DropDownListFor行是导致NullReferenceExceptions的原因。
<div class="form-group">
@Html.LabelFor(m => m.carrierListIndex, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m=>m.carrierListIndex, Model.carrierList.Select(Text = x.name, Value = x.Id.ToString(), Selected = Model.CarrierListIndex == x.Id), "Please Select...",null)
</div>
</div>
This is the portion of RegisterViewModel that corresponds to carriers: 这是RegisterViewModel对应于运营商的部分:
[Display(Name = "Wireless Carrier")]
public int carrierListIndex { get; set; }
public static db db = new db();
public List<Carrier> carrierList = db.Carriers.ToList();
My two Register functions in AccountController.cs: 我在AccountController.cs中的两个Register函数:
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email, studentID = model.studentID, phone=model.phone, carrierList=model.carrierList };
var result = await UserManager.CreateAsync(user, model.Password);
var context = new ApplicationDbContext();
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)
{
userManager.AddToRole(user.Id, "User");
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);
}
The 2nd argument of DropDownListFor()
is Ienumerable<SelectListItem>
but you just passing an anonymous object. DropDownListFor()
的第二个参数是Ienumerable<SelectListItem>
但您只是传递一个匿名对象。 Change the view model to 将视图模型更改为
public class RegisterViewModel
{
....
[Display(Name = "Wireless Carrier")]
[Required(ErrorMessage = "Please select a carrier")]
public int SelectedCarrier { get; set; }
public IEnumerable<SelectListItem> CarrierList { get; set; }
}
and pass the model to the view in the GET method 并将模型传递给GET方法中的视图
[AllowAnonymous]
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // must reassign the SelectList
return View(model);
}
.... // save and redirect
}
private ConfigureViewModel(RegisterViewModel model)
{
model.carrierList = new SelectList(db.Carriers, "Id", "name");
}
and in the view 并在视图中
@model RegisterViewModel
....
@Html.DropDownListFor(m => m.SelectedCarrier, Model.CarrierList,"Please select")
@Html.ValidationMessageFor(m => m.SelectedCarrier)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.