The function @Html.ValidationMessageFor did not function as planned.

asp.net-mvc c# entity-framework validation

Question

I have two model classes with one-to-many relationships.

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

Sharp file.

    <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) The first issue I have is that the Validation function did not activate when I selected the Select Cycle Type, and it merely returned an error as

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

2) The second issue arises when I choose a cycle type and input more than 20 characters in the model to enable the validator to do the necessary check. But I keep receiving the same problem message.

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

We welcome any recommendations.

1
1
1/12/2012 5:43:17 AM

Accepted Answer

Because of a fault in Asp.net MVC, the validations for the extension methods DropDownListFor and TextAreaFor don't function.

The information is available at http://aspnet.codeplex.com/workitem/8576.

Consequently, you must utilize HTML. If you use DropDownList rather than DropDownListFor, your validations will function as anticipated.

Update

Pass this along from your controller.

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

then use this in View

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

Further Update

There is yet one more solution to this issue.

just apply your unique code ofDropDownListFor . Just use the class property as follows after that.

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

The validation will function as a result, however the default message of The box must be checked. will be shown. Otherwise, everything will go as you anticipate.

This is probably a superior option and a suitable fit for your needs.

5
1/12/2012 8:06:12 AM

Popular Answer

I respond to my own question because I don't want anybody else to run into the same issue that I did.

First off, let me to thank @Pankaj Upadhyay for all of his assistance. I really appreciate your help, @Pankaj Upadhyay.

Finally, with Pankaj Upadhyay's ongoing assistance, I was able to resolve my issue.

@model CyclingClubSystem.Models.CycleModel

@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

}

<h2>Edit</h2>

<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>
    <legend>CycleModel</legend>

    @Html.HiddenFor(model => model.CycleModelID)

    <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", @class = "required" })*@

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

        @*Html.DropDownList("CycleType", "Select Cycle Type")*@
        @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>

    <p>
        <input type="submit" value="Save" />
    </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Controlling Type

    [HttpGet]
    public ActionResult Edit(int CycleModelID)
    {
        CycleModel cycleModel = unitOfWork_CycleModel.GenericTEntityRepository.GetByID(CycleModelID);
        //ViewBag.CycleType = new SelectList(unitOfWork_cycleType.GenericTEntityRepository.Get(orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)), "CycleTypeID", "Type", cycleModel.CycleTypeID);
        ViewBag.CycleType = new SelectList(unitOfWork_cycleType.GenericTEntityRepository.Get(orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)), "CycleTypeID", "Type");
        return View(cycleModel);
    }

    [HttpPost]
    public ActionResult Edit(CycleModel  _CycleModel)
    {
        if (ModelState.IsValid)
        {
            unitOfWork_CycleModel.GenericTEntityRepository.Update(_CycleModel);
            unitOfWork_CycleModel.Save();
            return RedirectToAction("Index");
        }
        ViewBag.CycleType = new SelectList(unitOfWork_cycleType.GenericTEntityRepository.Get(orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)), "CycleTypeID", "Type");
        return View(_CycleModel);
    }

Finally, I discovered that the primary source of the issue was my failure to include the code in the [Controller Edit Post method] body.

ViewBag.CycleType = new SelectList(unitOfWork_cycleType.GenericTEntityRepository.Get(orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)), "CycleTypeID", "Type");

The reason I can fix my difficulty is because I get ongoing advice from @Pankaj Upadhyay.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow