为什么MVC默认验证每次都被触发?

时间:2014-04-12 18:24:13

标签: c# validation asp.net-mvc-4

我的代码中有这个:

这是我的模特。

public class CompanywiseReportModel
    {
        [DisplayName("Company Name")]
        public int ClientDetailId { get; set; }

        [DisplayName("Company Name")]
        public string CompanyName { get; set; }

        public IEnumerable<SelectListItem> CompanyNameList { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime FromDate { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime ToDate { get; set; }
    }

这是我的观点:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <div class="divpageTitle">
        <asp:Label ID="lblPageTitle" runat="server" Text="Company Wise Report"></asp:Label>
    </div>

    <% Html.EnableClientValidation();%>
    <% using (Html.BeginForm("GenerateCompanywiseReport", "Report", FormMethod.Post, new { target = "_blank" }))
       { %>
    <div id="clientdetail">
        <div class="clientform">
            <asp:Panel ID="Panel1" GroupingText="Company Wise Report" runat="server">
                <div class="innerForm">
                    <div class="editor-label">
                        <%: Html.LabelFor(model => model.ClientDetailId,"Company Name") %>
                    </div>
                    <div class="editor-field">
                        <%: Html.DropDownListFor(model => model.ClientDetailId,Model.CompanyNameList) %>

                        <%: Html.ValidationMessageFor(model => model.ClientDetailId) %>
                    </div>

                    <div class="editor-label">
                        <%: Html.LabelFor(model => model.FromDate,"From Date") %>
                    </div>
                    <div class="editor-field">
                        <%: Html.TextBoxFor(model => model.FromDate ,new { @class = "datePickerControl" }) %>
                        <%: Html.ValidationMessageFor(model => model.FromDate) %>
                    </div>

                    <div class="editor-label">
                        <%: Html.LabelFor(model => model.ToDate,"To Date") %>
                    </div>

                    <div class="editor-field">
                        <%: Html.TextBoxFor(model => model.ToDate ,new { @class = "datePickerControl" }) %>
                        <%: Html.ValidationMessageFor(model => model.ToDate) %>
                    </div>

                    <div class="editor-label">
                        &nbsp;
                    </div>
                    <div class="editor-label">
                        &nbsp;
                    </div>
                    <div class="editor-field">
                        <input type="submit" value="Generate Report" />
                        <input type="button" value="Cancel" onclick="javascript: location.href = '/ClientDetail/Index';" />
                    </div>
                </div>
            </asp:Panel>
            <% } %>
        </div>
    </div>
    <uc:warning ID="ucWarning" runat="server" /></asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="ScriptsSection" runat="server">
    <%: Scripts.Render("~/bundles/jqueryval") %>
    <%: Scripts.Render("~/bundles/FeedbackwiseReport") %>
</asp:Content>

这是附加的javascript:

$(function () {
    $(".datePickerControl").datepicker({
        showOn: "button",
        buttonImage: "../../images/calendar.gif",
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy'
    }).datepicker('setDate', null);

});

这是我的控制器的相关代码:

public ActionResult CompanywiseReport()
        {
            CompanywiseReportModel objCompanywiseReportModel = new CompanywiseReportModel();
            FeesDetailHelper objFeesDetailHelper = new FeesDetailHelper();
            objCompanywiseReportModel.CompanyNameList = objFeesDetailHelper.GetCompanies(0);
            return View(objCompanywiseReportModel);

        } 

[HttpPost]
        public ActionResult GenerateCompanywiseReport()
        {
            TrainingFeedBackDetailHelper objTrainingFeedBackDetailHelper = new TrainingFeedBackDetailHelper();

            LocalReport localReport = new LocalReport();
            ReportDataSource reportDataSource = new ReportDataSource();
            localReport.ReportPath = Server.MapPath("~/Views/Report/companywise.rdlc");
            reportDataSource.Name = "CompanywiseReportDataset";
            int trainingDetailId = Convert.ToInt16(Request["ClientDetailId"]);

            String Fromdate = Request["FromDate"];
            String Todate = Request["ToDate"];
            DateTime from;
            DateTime to;
            if (Fromdate == null)
            {
                from = new DateTime(01, 01, 01);
            }
            else
            {
                if (Regex.IsMatch(Fromdate, @"^([0-9]{2})\/([0-9]{1})\/([0-9]{4})$"))
                {
                    Fromdate = (Fromdate.Insert(3, "0"));
                }
                from = DateTime.ParseExact(Fromdate, "dd/MM/yyyy", CultureInfo.CurrentCulture);
            }
            if (Todate == null)
            {
                to = new DateTime(01, 01, 01);
            }
            else
            {
                if (Regex.IsMatch(Todate, @"^([0-9]{2})\/([0-9]{1})\/([0-9]{4})$"))
                {
                    Todate = (Todate.Insert(3, "0"));
                }
                to = DateTime.ParseExact(Todate, "dd/MM/yyyy", CultureInfo.CurrentCulture);
            }

            reportDataSource.Value = objTrainingFeedBackDetailHelper.GetCompanyWiseReportData(trainingDetailId,from,to);
            localReport.DataSources.Add(reportDataSource);

            string reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;

            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
            "<DeviceInfo>" +
            "  <OutputFormat>PDF</OutputFormat>" +
            "  <MarginTop>0.2in</MarginTop>" +
            "  <MarginLeft>0.2in</MarginLeft>" +
            "  <MarginRight>0.2in</MarginRight>" +
            "  <MarginBottom>0.2in</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
            //Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension);
            return File(renderedBytes, mimeType);
        }

Opppps ..我的问题太长了,但请耐心等待!! !!

我的问题是每当我尝试使用此视图执行任何操作时,模型都会失效。我的控制器甚至没有从我的视图中点击。我不知道这是从哪里来的。我被困住了,无法找到解决方法。对此的任何帮助都非常值得注意。谢谢.. !!

1 个答案:

答案 0 :(得分:1)

在VS中将断点放在if(ModelState.IsValid)行中,然后检查模型中的值以查看导致错误的原因。