当我将带有POST的视图模型发送到我的控制器(没有选择城市)时,我得到了一个预期的"所需的城市"错误但是当我选择一个城市(比如列表中的第一个)然后我有另一个错误(例如缺少名字)所以我的模型状态仍然无效它将我重定向到初始页面并从底部突然选择一些城市(或有时随机)
在视图中
@Html.DropDownListFor(m => m.CityID, Model.SelectListCities, "Select City", new { @class = "form-control", @name = "City" })
在控制器中
public ActionResult Registration()
{
RegisteredVisitorVM Model = new RegisteredVisitorVM();
List<City> cities = principal.Cities.ToList().OrderBy(x => x.Name).ToList();
List<SelectListItem> cityList = new List<SelectListItem>();
cityList.AddRange(cities.Select(
x => new SelectListItem { Value = x.CountryID.ToString(), Text = x.Name }
).ToList()
);
Model.SelectListCities = cityList;
return View("RegistrationView", Model);
}
public ActionResult SubmitRegisteredVisitors(RegisteredVisitorVM model)
{
if (!ModelState.IsValid)
{
List<SelectListItem> cityList = new List<SelectListItem>();
List<City> cities = principal.Cities.ToList().OrderBy(x => x.Name).ToList();
cityList.AddRange(cities.Select(
x => new SelectListItem { Value = x.CountryID.ToString(), Text = x.Name }
).ToList()
);
model.SelectListCities = cityList;
return View("RegistrationView", model);
}
return Content(model.FirstName);
}
在ViewModel中
using CondorExtreme3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CondorExtreme3.Areas.Users.Models
{
public class RegisteredVisitorVM
{
[MaxLength(50, ErrorMessage = "First name is too long!")]
[Required(ErrorMessage = "First name is required!")]
public string FirstName { get; set; }
[MaxLength(50, ErrorMessage = "Last name is too long!")]
[Required(ErrorMessage = "Last name is required!")]
public string LastName { get; set; }
[Index(IsUnique = true)]
[MaxLength(30, ErrorMessage = "Username is too long!")]
[Required(ErrorMessage = "Username is required!")]
public string UserName { get; set; }
[MaxLength(30, ErrorMessage = "Password is too long!")]
[MinLength(8, ErrorMessage = "Must have at least 8 characters!")]
[RegularExpression("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{2,}$", ErrorMessage = "Must be alpha-numeric!")]
[Required(ErrorMessage = "Password is required!")]
public string Password { get; set; }
[Required(ErrorMessage = "Phone number is required!")]
public string PhoneNumber { get; set; }
[Index(IsUnique = true)]
[Required(ErrorMessage = "Email is required!")]
[RegularExpression("^[^@]+@[^@]+\\.[^@]+$", ErrorMessage = "Invalid format!")]
public string Email { get; set; }
[Required(ErrorMessage = "City is required!")]
public int CityID{ get; set; }
public List<SelectListItem> SelectListCities { get; set; }
}
}
答案 0 :(得分:1)
Hej Ilhan, 当我为大学创建一些研讨会工作时,我遇到了这个问题。
第一次在验证失败时我没有重新填充列表,第二次是inteli sense创建问题时,我在重新启动VS后才解决。 简而言之,如果您使用Code First,您确定var名称是“CountryID”而不是“CountryId”吗? :d