部分视图中的MVC3客户端验证

时间:2012-09-20 12:18:05

标签: asp.net-mvc asp.net-mvc-3 jquery-validate data-annotations asp.net-mvc-partialview

我有一个视图索引和一个部分视图SCItems。我使用数据注释进行验证。它适用于Index,但不适用于我的部分SCItem。我应该使用jquery验证?谢谢。 SCModel代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.WebPages.Html;

namespace PunchClockMobile.Models
{
    public class SCModel
    {
        public List<string> scList = new List<string>();

        [Required(ErrorMessage = "SC ID cannot be empty!")]
        public string scID { get; set; }

        [StringLength(4, ErrorMessage = " Please use 4 characters ")]
        [Range(0, 24, ErrorMessage = " Please use 0-24 range ")]
        [Required(ErrorMessage = "Please enter work duration")]
        public double? Duration { get; set; }

        [Required(ErrorMessage = "Please select a date")]
        public DateTime? Date { get; set; }

        [Required(ErrorMessage = "No task selected!")]
        private List<SelectListItem> _task = new List<SelectListItem>();

        [Required(ErrorMessage = "No task selected!")]
        public string SelectedTask { get; set; }

        [Required(ErrorMessage = "No task selected!")]
        public List<SelectListItem> Task
        {
            get { return _task; }
        }

    }
}

索引代码:

@model PunchClockMobile.Models.SCModel
@{
    ViewBag.Title = "SC Number";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Header {
    <h3 style="text-align: left; padding-left: 1px;">
        SC Number</h3>
}
<div data-role="content" class="ui-content" role="main">
    @using (Html.BeginForm())
    {  <fieldset>
          <div data-role="fieldcontain">
        <label class="select">
            SC Number:</label>
        @Html.TextBoxFor(m => m.scID, new { @data_inline = true, @Class = "scIDFormat" })
        <br />
        <br />
        @Html.ValidationMessageFor(m => m.scID)
        <button type="submit" id="scOK" name="scOK">
            OK</button>
        </div>
        <div id="scList">
        </div>
      </fieldset>
       }
    </div>

<script language="javascript" type="text/javascript">

    $(document).ready(function () {
 $("#scOK").click(function () {

            if ($("form").valid()) {
                GetSCItems();
                $("#scList").show();
            }
            return false;
        });
 function GetSCItems() {
        var action = '@Url.Action("GetSCItems", "SCNumber")';
        var scID = $("#scID").val();
        var opt = {
            type: "GET",
            data: { ID: scID },
            url: action,
            success: SCListSuccess,
            error: SCListFailed
        };
        jQuery.ajax(opt);
    }

    function SCListSuccess(data) {
        if (data != undefined) {
            $('#scList').html(data).trigger('create');
            $("#noValues").hide();
        }
        else {
            //error
        }
    }

    function SCListFailed() {
        //error
    }
   });
</script>

SCItems代码:

@model PunchClockMobile.Models.SCModel
@if (@Model.scList.Count != 0)
{

        <div data-role="fieldcontain">
            @Html.TextBoxFor(m => m.scID, new { @id = "scID", Class = "hidden" })
            <strong>@Html.Label("SC DESC:")</strong>
            @Html.TextBoxFor(m => m.scList[5], new { @id = "desc", @dbID = Model.scList[5], data_inline = "true", @readonly = "true", @class = "required" })
        </div>
        <div data-role="fieldcontain">
            <strong>@Html.Label("Product:")</strong>
            @Html.TextBoxFor(m => m.scList[6], new { @id = "prod", @dbID = @Model.scList[2], data_inline = "true", @readonly = "true", Class = "results" })
        </div>
        <div data-role="fieldcontain">
            <strong>@Html.Label("Account:")</strong>
            @Html.TextBoxFor(m => m.scList[7], new { @id = "acc", @dbID = @Model.scList[3], data_inline = "true", @readonly = "true", Class = "results" })
        </div>
        <div data-role="fieldcontain">
            <strong>@Html.Label("Project:")</strong>
            @Html.TextBoxFor(m => m.scList[8], new { @id = "proj", @dbID = @Model.scList[4], data_inline = "true", @readonly = "true", Class = "results" })
        </div>
        <div data-role="fieldcontain">
            @Html.Label("Task:  *")
            @Html.DropDownListFor(x => x.SelectedTask, new SelectList(Model.Task, "Value", "Text"), "Please Select a task", new { @Class = "required" })
            @Html.ValidationMessageFor(x => x.SelectedTask)
        </div>
        <div data-role="fieldcontain">
            <strong>@Html.Label("Date: *")</strong>
            @Html.TextBoxFor(m => m.Date, new { @data_role = "datebox", @autocomplete = "off", @Class = "required", @data_options = " {'mode':'calbox','overrideDateFormat': 'YYYY/mm/dd'" })
            @Html.ValidationMessageFor(m => m.Date)
        </div>
        <div data-role="fieldcontain">
            <strong>@Html.Label("Duration: *")</strong>
            @Html.TextBoxFor(m => m.Duration, new { @maxlength = "4", @Class = "required", @autocomplete = "off" })
            @Html.ValidationMessageFor(m => m.Duration)
        </div>
        <div id="ajaxPostMessage" class="ajaxMessage">
        </div>
        <div data-role="fieldcontain" align="center">
            <div class="search-button">
                <input type="submit" id="add" value="Add record" />
            </div>
        </div>

}

else
{
    <div class="ajaxMessage">
        @ViewBag.OpenID
    </div>
}
<script type="text/javascript">

    $(document).ready(function () {
        $("#Duration").bind('keypress', function (e) {
            return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) ? false : true;
        });

        $("#ajaxPostMessage").hide();
        //GetTask method from SCNumber controller
        $.get('SCNumber/GetTask/' + $("#prod").attr('dbID'), function (response) {
            var task = $.parseJSON(response);
            var ddlSelectedTask = $("#SelectedTask");
            // clear all previous options 
            $("#SelectedTask > option").remove();
            // populate the task 
            for (i = 0; i < task.length; i++) {
                ddlSelectedTask.append($("<option />").val(task[i].Value).text(task[i].Text));
            }
        });

        $("#add").click(function () {
            $.validator.unobtrusive.parse($('form'));  //added
            if ($("form").valid()) {
                var IDs = new Array($("#prod").attr('dbID'), $("#acc").attr('dbID'), $("#proj").attr('dbID'), $("#SelectedTask").val(), $("#Date").val(), $("#Duration").val(), $("#desc").attr('dbID'), $("#scID").val());
                $.ajax({
                    url: '@Url.Action("HandleForm", "SCNumber")',
                    type: 'post',
                    data: { ids: IDs },
                    dataType: 'json',
                    traditional: true,
                    success: function (data) {
                        if (data.success == true) {
                            window.location.href = '@Url.Action("Index", "SCNumber")';
                        }
                        else {
                            $("#ajaxPostMessage").html(data.Error);
                            $("#ajaxPostMessage").show();
                        }
                    }
                });
            }
            return false;
        });
    });
</script>

2 个答案:

答案 0 :(得分:1)

尝试查看以下帖子,您可能遇到同样的问题:

MVC 3 Razor. Partial View validation is not working

希望这有帮助

答案 1 :(得分:0)

在MVC3中,部分视图的返回类型是“ MVCHTMLString ”,我们可以在服务器端捕获此字符串并对其应用验证。 在您的控制器中

 protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

通过将ViewName和Model传递给此方法,它将返回视图的“ MVCHTMLString ”,因此可以在模型中应用验证。 并使用Ajax.BeginForm而不是Html.BeginForm来提交局部视图。 所以在你的paratil视图中

      @using (Ajax.BeginForm("GetSCItems", "SCNumber", new AjaxOptions { OnSuccess = "AddSearch", UpdateTargetId = "scList" }))
     {
        <input type="submit" value="save"/>
     } 

在控制器

public ActionResult GetSCItems(SCModel model)
{
     // operation 
     return RenderPartialViewToString("SCItems",model)
}
AjaxOption中的

将“ UpdateTargetId ”指定为scList,其结果将附加到其中。