![](/img/trans.png)
[英]how to bind model value to selected item text from dropdownlist mvc4
[英]MVC4 Validate Item Selected In DropDownList
我有一個頁面來創建objects
,並且在其中有一個DropDownList
。 如果我從列表中選擇一個項目,我的頁面將正確保存,但是,如果我不選擇一個項目,則它似乎在回發時失敗,因為對象將為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 [“ error”]
附加代碼模型:
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
[必需(ErrorMessage =“必須選擇一個對象”)
公共SelectList AllObjects {get;
組;
}
您的模型應該是
[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);
}
您的Post控制器:
[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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.