gpt4 book ai didi

c# - @Html.ValidationMessageFor 没有按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 18:14:30 24 4
gpt4 key购买 nike

我有两个具有一对多关系的模型类。

public class CycleType
{
[Required(ErrorMessage = "Cycle is required.")]
public int CycleTypeID { get; set; }

[Required(ErrorMessage = "Cycle Type is required.")]
[StringLength(20, ErrorMessage = "Cycle Type may not be longer than 20 characters")]
public string Type { get; set; }

public List<CycleModel> CycleModels { get; set; }
}

public class CycleModel
{
public int CycleModelID { get; set; }

[DisplayName("Cycle Type")]
[Required(ErrorMessage = "Cycle is required.")]
public int CycleTypeID { get; set; }

[Required(ErrorMessage = "Model is required.")]
[StringLength(20, ErrorMessage = "Model may not be longer than 20 characters")]
public string Model { get; set; }

public virtual CycleType CycleType { get; set; }
}

Razor 文件。

    <div class="editor-label">
@Html.LabelFor(model => model.CycleTypeID)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CycleTypeID,
(SelectList)ViewBag.CycleType,
"Select Cycle Type",
new { id = "ddlCycleType" })
@Html.ValidationMessageFor(model => model.CycleTypeID)
</div>


<div class="editor-label">
@Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model)
@Html.ValidationMessageFor(model => model.Model)
</div>

1) 我的问题是,当我选择选择循环类型时,Validaion 函数没有触发,它只返回错误

The ViewData item that has the key 'CycleTypeID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

2) 第二个问题是,当我选择其中一种循环类型并将值放入超过 20 个字符的模型中,以便验证器可以按我的预期进行检查。但是我再次收到相同的错误消息。

The ViewData item that has the key 'CycleTypeID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

我们将不胜感激。

最佳答案

嗯,这是 Asp.net MVC 中的一个错误,因此验证不适用于 DropDownListFor 和 TextAreaFor 扩展方法。

您可以在http://aspnet.codeplex.com/workitem/8576查看详情

因此,您将需要使用 HTML.DropDownList 而不是 DropDownListFor,然后您的验证将按预期工作。

更新

从你的 Controller ,传递这个

ViewBag.CycleTypeId = new SelectList(db.CycleTypes, "CycleTypeId", "Type"); // db is ur context instance

在 View 中使用这个

@Html.DropDownList("CycleTypeId", String.Empty)

更多更新

这个问题还有一个解决方法。

只需使用您的原始代码 DropDownListFor。然后像下面这样使用类属性

 @Html.DropDownListFor(model => model.CycleTypeID,
(SelectList)ViewBag.CycleType,
"Select Cycle Type",
new { id = "ddlCycleType", @class = "required" })

这将使验证生效,但它会显示默认消息The field is required。但 else 将按您预期的那样工作。

我想这是一个更好的解决方案,也很适合您的要求。

关于c# - @Html.ValidationMessageFor 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com