我正在研究Asp.Net MVC,部分视图上的数据注释不起作用

时间:2017-01-28 10:53:31

标签: asp.net-mvc

代码背景

在我的应用程序中,我在主视图中的主视图中附加了按钮单击的部分视图。部分视图包含取消按钮,该按钮在其单击时从主视图中删除部分视图。我的提交按钮位于主视图中,它从视图,主要和部分提交数据。部分视图上的.Data注释无效。

任何帮助都将不胜感激。

我的父模型(StudentDetails)如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using PartialViewDemo.Models;

namespace PartialViewDemo.Models
{
   public class StudentDetails
     {
    [Required(ErrorMessage ="Required")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Required")]
    public string LastName { get; set; }
    [Required(ErrorMessage = "Required")]
    public string StudentId { get; set; }
    [Required(ErrorMessage = "Required")]
    public int Age { get; set; }
    [Required(ErrorMessage = "Required")]
    public string Email { get; set; }

    public IList<PartialAddress1> addressList { get; set; }
    }

}

子模型(PartialAddress1)如下

 public class PartialAddress1
{
    [Required(ErrorMessage ="Required")]
    public string AddressType { get; set; }
    [Required(ErrorMessage ="Required")]
     public string Address { get; set; }
    public Guid UniqueID { get; set; }

    public PartialAddress1()
    {
        UniqueID = Guid.NewGuid();
    }

}

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartialViewDemo.Models;

namespace PartialViewDemo.Controllers
{
   public class StudentController : Controller
{
    StudentDetails student = new StudentDetails();
    PartialAddress1 address1 = new PartialAddress1();
    Services service = new Services();
    // GET: Student
    public ActionResult Index()
    {
        List<StudentDetails> listt = new List<StudentDetails>();
        listt = service.GetRecords();
        if (listt.Count < 1)
        {
            ViewData.Model = listt;
            return View(ViewData.Model);
        }
        ViewData.Model = listt;
        //ViewBag.Personrecords = records;
        return View();
    }

    public ActionResult StudentDetails()
    {
        return View();
    }

    [HttpPost]
    public ActionResult StudentDetails(StudentDetails details)
    {

            student.FirstName = details.FirstName;
            student.LastName = details.LastName;
            student.StudentId = details.StudentId;
            student.Age = details.Age;
            student.Email = details.Email;
            student.addressList = details.addressList;

            service.AddStudent(student);


            return RedirectToAction("Index");

    }

    public  PartialViewResult ShowPartialView()
    {
        PartialAddress1 address1 = new PartialAddress1();
        return PartialView("PartialView", address1);
    }


}

}

主视图(学生详细信息)

@model PartialViewDemo.Models.StudentDetails

@{
   ViewBag.Title = "StudentDetails";
 }
   <head>
  <script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>


<script type="text/javascript">
    function deleteAddress(Id) {
        Id.remove();
    }


    $(function () {
        $("#btnClick").click(function () {
            $.post("/Student/ShowPartialView",

                function (response) {
                    $('#view').append(response);

                }
             );
        });
       return false;
    });

    $(function () {
        $('#submit').click(function () {
            alert('calling');
            if ($(this).valid()) {
                var $form = $('#@Model.');
                $("form").data("unobtrusiveValidation", null);
                $("form").data("validator", null);
                $.validator.unobtrusive.parse($("form"));
            }

        });
    });


</script>

</head>

  <h2>StudentDetails</h2>



   @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform"     }))
 {
   @Html.AntiForgeryToken()

<div class="form-horizontal" >
    <h4>StudentDetails</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, htmlAttributes: new {     @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FirstName, "", new {  @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.StudentId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.StudentId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.StudentId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>


    <div>Add Address :<input type="button" value="Add" id="btnClick" />   </div>/////button to add partial view

    <div id="view">

    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">

            <input  type="submit" value="Submit" class="btn btn-default" id="submit"  />//////button that submits form (main and child view)

        </div>
    </div>
  </div>
}

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



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

我的孩子视图(PartialView.cshtml)

@model PartialViewDemo.Models.PartialAddress1
@using HtmlHelpers.BeginCollectionItem

<head>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>


</head>


@using (Html.BeginCollectionItem("addressList"))
{
    @Html.ValidationSummary(true)

    @Html.AntiForgeryToken()

    <div class="form-horizontal" id="@Model.UniqueID" >

        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.AddressType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AddressType, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AddressType, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>




        <div><input type="button" value="Cancel" id="cancel" name="Cancel" onclick="deleteAddress(document.getElementById('@Model.UniqueID'));" /></div>
    </div>
}



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

当我提交表单时,只有主视图数据注释正在工作。如何使部分视图数据注释正常工作。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,问题是模型dataBinder找不到对象列表的属性&#34; PartialAddress1&#34;,结果你的details.addressList;在操作方法中为空

StudentDetails(StudentDetails details)

Bacause addressList是IList<PartialAddress1>

您应该在视图输入中使用followind名称: 对于&#34; PartialAddress1&#34;的第一个对象:

<input name="[0].AddressType " type="text" value="" />
<input name="[0].Address " type="text" value="" />

第二名:

<input name="[1].AddressType " type="text" value="" />
<input name="[1].Address " type="text" value="" />

在这种情况下,modelBinder可以找到这些属性。 在您的部分视图中,您可以这样做:

using (Html.BeginForm())
{
    for (int i = 0; i < 2; i++)
    {
        <fieldset>
            <legend>object  @(i + 1)</legend>
            <div><label>AddressType:</label>
                @Html.Editor("[" + i + "].AddressType")
            </div>
            <div><label>Address:</label>
                @Html.Editor("[" + i + "].Address")
            </div>
        </fieldset>
    }

}