を作成するページが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();
}
}
上記のコードは作成ページに移動するだけですが、エラーは表示されません。Create の 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>
}