在 mvc 中使用数据注释进行验证不起作用

发布于 2024-11-19 14:24:44 字数 3835 浏览 2 评论 0原文

我已经创建了带有验证的视图模型,但是当我提交表单时验证不起作用,下面是代码:

namespace Products.Models
{
[MetadataType(typeof(SampleFormViewModelMetaData))]
public partial class SampleFormViewModel
{
    public SampleFormViewModel() { }

    public Venue venues { get; set; }
    public Accomodation accomodation { get; set; }
}

public class SampleFormViewModelMetaData
{


    [Required(ErrorMessage = "*")]
    public object ProductName { get; set; }

    [Required(ErrorMessage = "*")]
    public object ProductDescription { get; set; }

    [Required(ErrorMessage = "*")]
    public object ProductWebsite { get; set; }

    [Required(ErrorMessage = "Tel required")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public object ProductTel { get; set; }
}

}

View

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ApexAdmin.Master" Inherits="System.Web.Mvc.ViewPage<ApexTrackDays.Models.SampleFormViewModel>" %>
            <div class="editor-label">
            <%: Html.LabelFor(model => model.accomodation.ProductName)%>
        </div>
        </td>
        <td>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.accomodation.ProductName, new { style = "width:300px;" })%>
            <%: Html.ValidationMessageFor(model => model.accomodation.ProductName)%>
        </div>
        </td>
        </tr>

        <tr><td colspan="2">
        <div class="editor-label">
            <%: Html.LabelFor(model => model.accomodation.ProductDescription)%>
        </div>
        </td>
        </tr><tr><td colspan="2">
        <div class="editor-field">
            <%: Html.TextAreaFor(model => model.accomodation.ProductDescription, new { @class = "tinymce" })%>
            <%: Html.ValidationMessageFor(model => model.accomodation.ProductDescription)%>
        </div>

       </td></tr>

        <tr><td>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.accomodation.ProductWebsite)%>
        </div>
        </td><td>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.accomodation.ProductWebsite, new { style = "width:300px;" })%>
            <%: Html.ValidationMessageFor(model => model.accomodation.ProductWebsite)%>
        </div>
        </td></tr> </table>

Controller

[HttpPost]
    public ActionResult Create(FormCollection formValues)
    {
       // ApextrackdaysEntities entity = new ApextrackdaysEntities();
        IAccomodationTypeRepository AccomodationResp = new AccomodationTypeRepository();
        ITrackRepository trackResp = new TrackRepository();
        IQueryable<Object> tracks = trackResp.GetVenuesSelectlist();
        ViewData["Venue"] = new SelectList(tracks, "VenueID", "Name");
        Accomodation accomodation = new Accomodation();
        if (TryUpdateModel(accomodation))
        {
            accomodation.DateAdded = DateTime.Now;
            accomodation.DateModified = DateTime.Now;
            accomResp.Add(accomodation);
            accomResp.Save();
            int AccomodationID = accomodation.ID;
            int VenueID = Convert.ToInt16(formValues["Venue"]);
            AccomodationType type = new AccomodationType();
            type.AccomodationID = AccomodationID;
            type.TrackID = VenueID;

            AccomodationResp.Add(type);
            AccomodationResp.Save();


            return RedirectToAction("Index", new { id = accomodation.ID });
        }
        return View(accomodation);

    }

I Have created view model with the validation in it, but the validation doesnt works when i submit the form, below is the code :

namespace Products.Models
{
[MetadataType(typeof(SampleFormViewModelMetaData))]
public partial class SampleFormViewModel
{
    public SampleFormViewModel() { }

    public Venue venues { get; set; }
    public Accomodation accomodation { get; set; }
}

public class SampleFormViewModelMetaData
{


    [Required(ErrorMessage = "*")]
    public object ProductName { get; set; }

    [Required(ErrorMessage = "*")]
    public object ProductDescription { get; set; }

    [Required(ErrorMessage = "*")]
    public object ProductWebsite { get; set; }

    [Required(ErrorMessage = "Tel required")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public object ProductTel { get; set; }
}

}

View

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ApexAdmin.Master" Inherits="System.Web.Mvc.ViewPage<ApexTrackDays.Models.SampleFormViewModel>" %>
            <div class="editor-label">
            <%: Html.LabelFor(model => model.accomodation.ProductName)%>
        </div>
        </td>
        <td>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.accomodation.ProductName, new { style = "width:300px;" })%>
            <%: Html.ValidationMessageFor(model => model.accomodation.ProductName)%>
        </div>
        </td>
        </tr>

        <tr><td colspan="2">
        <div class="editor-label">
            <%: Html.LabelFor(model => model.accomodation.ProductDescription)%>
        </div>
        </td>
        </tr><tr><td colspan="2">
        <div class="editor-field">
            <%: Html.TextAreaFor(model => model.accomodation.ProductDescription, new { @class = "tinymce" })%>
            <%: Html.ValidationMessageFor(model => model.accomodation.ProductDescription)%>
        </div>

       </td></tr>

        <tr><td>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.accomodation.ProductWebsite)%>
        </div>
        </td><td>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.accomodation.ProductWebsite, new { style = "width:300px;" })%>
            <%: Html.ValidationMessageFor(model => model.accomodation.ProductWebsite)%>
        </div>
        </td></tr> </table>

Controller

[HttpPost]
    public ActionResult Create(FormCollection formValues)
    {
       // ApextrackdaysEntities entity = new ApextrackdaysEntities();
        IAccomodationTypeRepository AccomodationResp = new AccomodationTypeRepository();
        ITrackRepository trackResp = new TrackRepository();
        IQueryable<Object> tracks = trackResp.GetVenuesSelectlist();
        ViewData["Venue"] = new SelectList(tracks, "VenueID", "Name");
        Accomodation accomodation = new Accomodation();
        if (TryUpdateModel(accomodation))
        {
            accomodation.DateAdded = DateTime.Now;
            accomodation.DateModified = DateTime.Now;
            accomResp.Add(accomodation);
            accomResp.Save();
            int AccomodationID = accomodation.ID;
            int VenueID = Convert.ToInt16(formValues["Venue"]);
            AccomodationType type = new AccomodationType();
            type.AccomodationID = AccomodationID;
            type.TrackID = VenueID;

            AccomodationResp.Add(type);
            AccomodationResp.Save();


            return RedirectToAction("Index", new { id = accomodation.ID });
        }
        return View(accomodation);

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

躲猫猫 2024-11-26 14:24:44

您应该使用元数据类将验证应用于现有模型字段/属性,因此:

namespace Products.Models
{

    [MetadataType(typeof(SampleFormViewModelMetaData))]
    public partial class SampleFormViewModel
    {
        public SampleFormViewModel() { }

        public Venue venues { get; set; }
        public Accomodation accomodation { get; set; }

        public object ProductName { get; set; }
        public object ProductDescription { get; set; }
        public object ProductWebsite { get; set; }
        public object ProductTel { get; set; }
    }

    public class SampleFormViewModelMetaData
    {


        [Required(ErrorMessage = "*")]
        public object ProductName { get; set; }

        [Required(ErrorMessage = "*")]
        public object ProductDescription { get; set; }

        [Required(ErrorMessage = "*")]
        public object ProductWebsite { get; set; }

        [Required(ErrorMessage = "Tel required")]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public object ProductTel { get; set; }
    }

}

--编辑--

进一步查看您的代码,似乎您正在尝试将验证应用于 Accommodation 类中的字段,而不是 SampleFormViewModel 。您似乎只有一个 Accommodation 实例,因此您的视图模型可能不应该将 Accommodation 对象传递给 View,而是应该提取字段并将它们呈现为视图模型(我不确定这是否可行)应该将元数据类应用于 Accommodation 对象,而不是 SampleFormViewModel。

You should use the metadata class to apply validate to existing model fields/properties thus:

namespace Products.Models
{

    [MetadataType(typeof(SampleFormViewModelMetaData))]
    public partial class SampleFormViewModel
    {
        public SampleFormViewModel() { }

        public Venue venues { get; set; }
        public Accomodation accomodation { get; set; }

        public object ProductName { get; set; }
        public object ProductDescription { get; set; }
        public object ProductWebsite { get; set; }
        public object ProductTel { get; set; }
    }

    public class SampleFormViewModelMetaData
    {


        [Required(ErrorMessage = "*")]
        public object ProductName { get; set; }

        [Required(ErrorMessage = "*")]
        public object ProductDescription { get; set; }

        [Required(ErrorMessage = "*")]
        public object ProductWebsite { get; set; }

        [Required(ErrorMessage = "Tel required")]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public object ProductTel { get; set; }
    }

}

--EDIT--

Looking at you code further it seems you are trying to apply validation to fields in the Accommodation class, not the SampleFormViewModel. You appear to only have a single Accommodation instance so your view model should probably not be passing the Accommodation object to the View but should extract the fields and present those as the view model alternatively (and I'm not sure if this would work) you should apply you metadata class to the Accommodation object, not the SampleFormViewModel.

若无相欠,怎会相见 2024-11-26 14:24:44

在您的 .cshtml 文件中包含 jqueryvalidate。例如,如果脚本已捆绑在您的 BundleConfig 文件中,那么您的代码将如下所示

@section scripts
 {
     @Scripts.Render("~/bundles/jqueryval")
 }

Include jqueryvalidate in your .cshtml file. For example, if the script has been bundled up in your BundleConfig file, then your code will look like this

@section scripts
 {
     @Scripts.Render("~/bundles/jqueryval")
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文