MVC4 验证在下拉列表中选择的项目
本文关键字:选择 项目 下拉列表 验证 MVC4 | 更新日期: 2023-09-27 18:31:09
>我有一个页面来创建objects
,在这个我有一个DropDownList
。 如果我从列表中选择一个项目,我的页面将正确保存,但是如果我不选择一个项目,它看起来在回发时失败,因为对象将为 null。
我想要的是尝试并验证用户是否已选择一个项目(默认为"请选择...")。
我有代码可以在控制器中检查并查看该项目是否为 null,但这就是我如何显示消息? 保留所有其他详细信息(如果存在)。
public ActionResult Create(int objectId = 0)
{
var resultModel = new MyObjectModel();
resultModel.AllObjects = new SelectList(_system.GetAllObjects(objectId));
// GetAllObjects juts returns a list of items for the drop down.
return View(resultModel);
}
[HttpPost]
public ActionResult Create(int? objectId, FormCollection collection)
{
try
{
int objectIdNotNull = 0;
if (objectId > 1)
{
objectIdNotNull = (int) objectId;
}
string objectName = collection["Name"];
int objectTypeSelectedResult = 1;
int.TryParse(collection["dllList"], out objectTypeSelectedResult);
if (!Convert.ToBoolean(objectTypeSelectedResult))
{
// So here I have discovered nothing has been selected, and I want to alert the user
return RedirectToAction("Create",
new {ObjectId = objectIdNotNull, error = "Please select an Object Type"});
}
....
return RedirectToAction(...)
}
catch
{
return View();
}
}
上面的代码只是转到"创建"页面,但不显示错误。 在我的创建视图中,我有以下行,我认为它会显示任何错误: @ViewData["错误"]
附加代码型:
using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace MyNameSpace
{
public class MyObjectModel
{
[Required(ErrorMessage = "Please select an Object Type")]
public SelectList AllObjects { get; set; } // I populate the drop down with this list
}
}
视图:
@model MyNameSpace.MyObjectModel
@{
ViewBag.Title = "Create";
}
<h2>Create </h2>
<p class="text-error">@ViewData["Message"]</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"> </script>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.MyObject.Name)
</div>
<div class="editor-field">
@Html.TextBoxFor(model=>model.MyObjectType.Name, new {style="width: 750px"})
@Html.ValidationMessageFor(model => model.MyObjectType.Name)
</div>
<div>
<label for="ddlList">Choose Type</label>
@if (@Model != null)
{
@Html.DropDownList("ddlList", Model.AllObjects, "Please Select...")
@Html.ValidationMessageFor(model => model.AllObjects, "An object must be selected", new { @class = "redText"})
}
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
您正在验证错误的SelectList
[必需(错误消息 ="必须选择对象")]
public SelectList AllObjects { get; set; }
您的模型应该是
[Required(ErrorMessage = "Please select an Object Type")]
public int ObjectId { get; set; }
public string ObjectName { get; set; }
您的控制器(不需要表单收集,这是MVC的重点)
public ActionResult Create(int Id = 0)
{
MyObjectModel resultModel = new MyObjectModel();
var ObjectResultList = _system.GetAllObjects(Id);
var ObjectSelectList = new SelectList(ObjectResultList, "id", "Name");
ViewBag.ObjectList = ObjectSelectList;
return View(resultModel);
}
您的后控制器:
[HttpPost]
public ActionResult Create(MyObjectModel o)
{
try
{
if (ModelState.IsValid)
{
//It's valid , your code here!
return RedirectToAction("ObjectCreated", new { id = o.objectId });
}
else
{
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
}
}
}
catch (Exception ex)
{
Response.Write(ex.InnerException.Message);
}
//If we get here it means the model is not valid, We're in trouble
//then redisplay the view repopulate the dropdown
var ObjectResultList = _system.GetAllObjects(objectId);
var ObjectSelectList = new SelectList(ObjectResultList, "id", "value");
ViewBag.ObjectList = ObjectSelectList;
return View(o);
}
您的视图应为强类型
<div class="editor-label">
@Html.LabelFor(model => model.ObjectId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.ObjectId,
(IEnumerable<SelectListItem>)ViewBag.ObjectList, "-- Select One Object --")
@Html.ValidationMessageFor(model => model.ObjectId)
</div>