我正在尝试创建一个基本注册表单,该注册表单从下拉列表中接收带有状态的地址。我似乎无法将下拉列表中的数据提取到包含状态对象的模型中。我尝试创建一个自定义模型绑定器,如下所示。当我调试 ModelState 是有效的,但状态始终为空。
楷模:
public class AccountInfo
{
public virtual Guid accoundID { get; set; }
public virtual string city { get; set; }
public virtual string email_address { get; set; }
public virtual string fax_number { get; set; }
public virtual string first_name { get; set; }
public virtual string last_name { get; set; }
public virtual string mailing_address { get; set; }
public virtual string phone_number { get; set; }
public virtual State state { get; set; }
public virtual string zip_code { get; set; }
}
public class State
{
public virtual int ID { get; set; }
public virtual string text { get; set; }
public virtual string value { get; set; }
}
模型粘合剂:
public class StateModelBinder : IModelBinder
{
private RepositoryDB Database;
public object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext
)
{
var key = bindingContext.ModelName + ".state";
var value = bindingContext.ValueProvider.GetValue(key);
if (value == null)
{
return null;
}
var result = new State();
Database = new RepositoryDB(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString);
try
{
var query = from s in Database.States
where s.value == value.ToString()
select new State()
{
text = s.text,
ID = s.ID,
value = s.value
};
result = (State)query.ToList().ElementAt(0);
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex.Message);
bindingContext.ModelState.SetModelValue(key, value);
}
return result;
}
控制器:
[HttpPost]
public ActionResult Index(AccountInfo accountModel)
{
try
{
if (ModelState.IsValid)
{
Database.Account.Add(accountModel);
Database.SaveChanges();
return Redirect(Url.Action("Success"));
}
}
catch (Exception ex)
{
ModelState.AddModelError(String.Empty, ex);
}
// invalid info - return with error message
//repop select lists
GetStates();
return View(accountModel);
}
public void GetStates()
{
IEnumerable<SelectListItem> states = from s in Database.States
select new SelectListItem
{
Text = s.text,
Value = s.value
};
ViewBag.state = states.ToList();
}
看法:
@Html.LabelFor(model => model.state, "*State")
@Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state)