0

出于某种原因,我在 mvc 3 中正确验证了相同的代码,但在 mvc 4 中从未调用客户端验证。本质上,我需要客户端验证才能在 jquery 模式对话框中工作。关于为什么不调用客户端验证的任何想法?

网页配置

<appSettings>
   <add key="webpages:Version" value="2.0.0.0" />
   <add key="webpages:Enabled" value="false" />
   <add key="PreserveLoginUrl" value="true" />
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

调用jquery对话框的代码

<script src="@Url.Content("~/Scripts/jquery-1.8.3.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.9.2.custom.min.js")" type="text/javascript"></script>
<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>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

<script>
    $(document).ready(function () {
        $('#lnk_report').click(function () {
            $('#dialog_report').dialog('open');

        });

        $.validator.unobtrusive.parse('#dialog_report');
        $('#dialog_report').dialog({
            position: {
                my: "center",
                at: "center",
            },
            autoOpen: false,
            width: 800,
            resizable: true,
            title: 'Report',
            modal: true,
            open: function (event, ui) {
                $(this).load('@Url.Action("CreateReport")');
            },
            buttons: {
                "Cancel": function () {
                    $(this).dialog("close");
                },
                "Submit": function () {
                    if ($('form').validate().form()) {
                        $.ajax({
                            url: '@Url.Action("CreateReport")',
                            type: 'POST',
                            data: $("form").serialize(),
                            success: function (result) {
                                $('#dialog_report').dialog("close");
                            }
                        });
                    }
                }
            }
        });


    });
</script>


@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>@ViewBag.Message</h2>
            </hgroup>
        </div>
    </section>
}

 <a id="lnk_report">Monthly Report</a>
 <div id="dialog_report" title="Report" style="overflow: hidden;"></div>

对话框代码

@model DefaultMvc4App.Models.ReportModel

<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)
    <table>
        <tr>
            <td>@Html.LabelFor(model => model.Month)</td>
            <td>@Html.DropDownListFor(model => model.Month, Model.AllMonths, "-- Select Month --")</td>
            <td>@Html.ValidationMessageFor(model => model.Month)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.Year)</td>
            <td>@Html.DropDownListFor(model => model.Year, Model.AllYears, "-- Select Year --")</td>
            <td>@Html.ValidationMessageFor(model => model.Year)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.GeneralMeeting)</td>
            <td>@Html.DropDownListFor(model => model.GeneralMeeting, Model.YesNo, "-- Select Answer --")</td>
            <td>@Html.ValidationMessageFor(model => model.GeneralMeeting)</td>
        </tr>
    </table>
}

报告模型

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;

namespace DefaultMvc4App.Models {
    public class ReportModel {
        [Key]
        public Guid ReportID { get; set; }

        [Required]
        public string Month { get; set; }
        public IEnumerable<SelectListItem> AllMonths {
            get { return new SelectList(Utils.GetMonths()); }
        }

        [Required]
        public string Year { get; set; }
        public IEnumerable<SelectListItem> AllYears {
            get { return new SelectList(Utils.GetYears()); }
        }

        [Required]
        public string GeneralMeeting { get; set; }
        public IEnumerable<SelectListItem> YesNo {
            get { return new SelectList(Utils.GetYesNo()); }
        }
    }
}

控制器代码

    [HttpPost]
    public ActionResult CreateReport(ReportModel report) {
        if (ModelState.IsValid) {
            try {
                report.ReportID = Guid.NewGuid();
                db.report.Add(report);
                db.SaveChanges();
                return Json(new { success = true });
            }
            catch (Exception e) {
                return Json(new { success = false });
            }
        }
        return Json(new { success = false });
    }
4

1 回答 1

0

示例展示如何将数据发布到控制器方法

剃刀代码:

<div id="form">
        <table width="600">
            <tr>
                <td>Select Date:</td>
                <td>
                    <input class="txtDate" type="date" size="20"></td>
            </tr>
            <tr>
                <td>Select Expense Type:</td>
                <td>
                    <select class="ExpenseType">
                        <optgroup label="Room">
                            <option>Room Fare</option>
                        </optgroup>

                        <optgroup label="Mess">
                            <option>Monthly Mess</option>
                        </optgroup>

                        <optgroup label="Others">
                            <option>Bus Fare</option>
                            <option>Tapari</option>
                            <option>Mobile Recharge</option>
                            <option>Auto</option>
                        </optgroup>
                    </select></td>
            </tr>
            <tr>
                <td>Enter Cost:</td>
                <td>
                    <input  class="cost" type="text" size="45" /></td>
            </tr>
            <tr>
                <td>Extra Details:</td>
                <td>
                    <input class="extra" type="text" size="45" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <button href="javascript:void(0);" onClick="saveExpense();" >Submit</button></td>
            </tr>
        </table>
    </div>

<script>
function saveExpense()
    {
        var expenseobject = {
            date:$('.txtDate').val() ,
            type:$('.ExpenseType').val() ,
            cost: $('.cost').val(),
            extra:$('.extra').val()

        };

        $.ajax({
            url: './saveexpense',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ obj: expenseobject }),
            success: function (result) {
                handleData(result);

            }
        });

    }
</script>

控制器:

 public ActionResult SaveExpense(Expense obj)
        {
            obj.ExpenseId = Guid.NewGuid();
            if (ModelState.IsValid)
            {
                context.expenses.Add(obj);
                context.SaveChanges();
                int total=context.expenses.Sum(x => x.cost);
                return Json(new {spent=total,status="Saved" });

            }
            else
                return Json(new { status="Error"});   
        }

费用是我的模型,其对象的字段被创建为 obj ......希望这会让你现在通过......

于 2012-12-12T20:37:30.537 回答