【发布时间】:2016-09-25 16:20:43
【问题描述】:
所以我认为这会非常简单,但我很难弄清楚。
首先,我将回顾一下到目前为止的内容。
RegisterViewModel:
public class RegisterViewModel
{
[Display(Name = "First Name:")]
public string FirstName { get; set; }
[Display(Name = "Last Name:")]
public string LastName { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email:")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password:")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password:")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Please choose the category that best describes your professional relation to the field of Orthotics and Prosthetics:")]
public List<string> ProfessionalRelations { get; set; }
[Display(Name = "Please check all of the following that apply to you:")]
public List<string> UserRelations { get; set; }
[Required]
[Display(Name = "Country")]
public SelectList Countries { get; set; }
[Required]
[Display(Name = "EDGE Direct E-mail Newsletter:")]
public List<string> EdgeNewsletter { get; set; }
}
注意国家选择列表。
现在,在我的控制器中。当有人进入注册页面时,我会按如下方式填充国家选择列表:
var countries = oandpService.GetCountries().OrderBy(x => x.CountryName).ToList();
var usa = countries.FirstOrDefault(x => x.CountryID == "US");
countries.Remove(usa);
countries.Insert(0, new Country() { CountryID = string.Empty, CountryName = string.Empty });
countries.Insert(1, usa);
rvm.Countries = new SelectList(countries, "CountryID", "CountryName");
最后,这是国家 DropDownListFor 视图的一部分:
@Html.DropDownListFor(x => x.Countries, Model.Countries, Model.Countries)
当您转到该页面时,这一切都显示正常。使用 CountryID 作为值和 CountryName 作为显示文本生成国家下拉列表。
然后,为了测试单选按钮、复选框和下拉菜单,我有以下内容:
[HttpPost]
[ValidateAntiForgeryToken]
[ReCaptchaFilter]
public ActionResult Register(RegisterViewModel rvm)
{
ViewBag.Countries = rvm.Countries.SelectedValue;
ViewBag.UserRelation = rvm.UserRelations;
ViewBag.ProfessionalRelation = rvm.ProfessionalRelations;
return View(rvm);
}
除了我在帖子中收到以下错误:
- 没有为此对象定义无参数构造函数。
- 没有为此对象定义无参数构造函数。对象类型“System.Web.Mvc.SelectList”。
谁能帮我指出正确的方向?我做了一些研究,但还没有弄清楚。任何意见都会非常感激。
【问题讨论】:
-
没有为这个对象定义无参数的构造函数。向你的控制器添加一个没有参数的构造函数
-
当人们第一次访问该页面(不是 HTTP 帖子)时,我已经有一个无参数构造函数。如果我尝试添加另一个 ActionResult Register() 它表示 AccountController 已经定义了一个名为 Register 的成员具有相同的参数类型。
-
所以我尝试通过在我的模型中创建一个名为 public Country Country {get;set;} 的新属性并将我的 DropDown 更改为:@Html.DropDownListFor(x => x.Country.CountryID,模型.国家);现在我得到了错误:对象引用未设置为对象的实例。
标签: c# asp.net-mvc asp.net-mvc-5 html.dropdownlistfor selectlist