0

我有一个要创建的页面objects,在这个页面中我有一个DropDownList. 如果我从列表中选择一个项目,我的页面将正确保存,但是如果我不选择一个项目,它看起来在回发时失败,因为对象将为空。

我想要的是尝试验证用户是否选择了一个项目(默认为“请选择...”)。

如果项目为空,我有代码将在控制器中检查并查看,但我该如何显示一条消息?保留所有其他详细信息(如果存在)。

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>
}
4

1 回答 1

3

您正在验证SelectList哪个是错误的

[Required(ErrorMessage = "必须选择一个对象")]
public 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);
}

你的后控制器:

[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>
于 2013-09-13T14:47:38.490 回答