【问题标题】:Partial View Validation Error getting trigger on partial view on view get call itself部分视图验证错误在视图获取调用本身的部分视图时触发
【发布时间】:2016-06-09 08:21:09
【问题描述】:

我有一个视图,它有两个部分视图,一个用于创建,另一个用于列出我使用视图模型作为主视图模型的项目

我的看法如下

@model Project.Web.Areas.Administrator.Models.VFranchise

<!-- content starts -->
<div class=" large-10 medium-10 small-10 columns band">
    <div class="row no-margin">
        <div class="content-head ">
            <!--breadcrumbs-->
            <ul>
                <li>@Html.ActionLink("Home", "GetAll")</li>
                <li>></li>
                <li>@Html.ActionLink("Franchise", "GetAll")</li>
                <li>></li>
                <li><a href="">Create New Franchise</a></li>
                <li>></li>

            </ul>
        </div>
        @{Html.RenderAction("CreateFranchise", "Franchise", Model.Franchise);}
        @{Html.RenderAction("ListAllFranchise", "Franchise", Model.Franchisees);}

    </div>
</div>

我的视图模型如下

public class VFranchise
{
    public Franchaise Franchise { get; set; }
    public IEnumerable<Franchaise> Franchisees { get; set; }
}

我要创建的部分视图如下

 @model Project.BAL.Models.Master.Franchaise

<div class="general-wrapper">
    <!--content box-->
    <div class="general-head">
        <h2 class="no-margin">Create New Franchise</h2>
        <div class="general-icons-org">
            <a href=""><i class="fa fa-minus"></i></a>
            <a href=""><i class="fa fa-square-o"></i></a>
            <a href=""><i class="fa fa-times"></i></a>
        </div>
    </div>
    @using (Html.BeginForm("Create", "Franchise", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <div class="minus-wrapper">
            <div class="org-general-wrapper">
                <div class="org-wrapper">
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <ul class="small-block-grid-1 medium-block-grid-2 large-block-grid-2">
                        <li>
                            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="inner">
                                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                            </div>
                        </li>

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

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

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

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

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

                        <li>
                            @Html.LabelFor(model => model.Status, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="inner">
                                @Html.DropDownListFor(m => m.Status, new List<SelectListItem>{
                                        new SelectListItem{ Text="Active", Value = "1" },
                                        new SelectListItem{ Text="Deactive", Value = "2" },
                                     }, new { @class = "form-control" })
                                @Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
                            </div>
                        </li>



                        <li>
                            <label>&nbsp;</label>
                            <div class="inner">
                                <input type="submit" value="Submit" class="btn btn-default" />
                            </div>
                        </li>
                    </ul>
                    <div class="req-wrapper">
                        <p>* required field</p>
                    </div>
                </div>
            </div>
        </div>
    }
    <div class="edit-wrapper">
        @Html.ActionLink("Back to List", "GetAll")
    </div>
</div>

这是我的主视图控制器

 public ActionResult Create()
 {
     return View(new VFranchise());
 }

这是我的 Post 方法

    [HttpPost]
    public ActionResult Create(Franchaise model)
    {
        if (ModelState.IsValid)
        {
            model.FranchaiseId = Guid.NewGuid();
            model.Status = Convert.ToInt32(model.Status);
            model.StartDate = DateTime.Now;
            _FranchaiseServices.Create(model);
            return RedirectToAction("GetAll");
        }
        else {
            var _model = new VFranchise();
            _model.Franchise = model;
            return View(_model);
        }

    }

这是我的部分视图控件

public PartialViewResult CreateFranchise(Franchaise model)
{
  return PartialView(model);
}

public PartialViewResult _ListFranchiseByExpiry(string id)
{
    int _id = Convert.ToInt32(id);
    var items = _FranchaiseServices.GetAllFranchiseByExpiry(_id);
    return PartialView(items);
}

问题是我在 HTTP get 调用 create 时遇到验证错误。

如果我这样做

public PartialViewResult CreateFranchise()
{
  return PartialView(new Franchaise());
}

我在帖子中也没有收到任何验证错误,请有人建议我在这里做错了什么。谢谢!

【问题讨论】:

  • 您在 CreateFranchise(Franchaise model) 方法上遇到验证错误,因为您将无效模型传递给该方法并且因为它包含验证属性,所以 DefaultModelBinder 添加了 ModelState 错误
  • 但是,如果我不这样做,即使在 HTTP 发布之后我也不会出错?
  • 您的方法是错误的,您需要使用视图模型 - 视图模型不包含属于数据模型的属性。我会在 30 分钟左右添加答案。
  • 非常感谢

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


【解决方案1】:

您在CreateFranchise(Franchaise model) 方法上收到验证错误的原因是您传递给该方法的模型包含验证属性并且其值无效(例如,您可能在string 属性上具有[Required] 属性,但是如果 null), so theDefaultModelBinderaddsModelState` 错误,则值会显示在视图中。

视图模型不应包含作为数据模型的属性,至少用于编辑)并且应该是

public class FranchaiseVM
{
    [Required(ErrorMessage = "Please enter a name")]
    public string Name { get; set; }
    .... // copy other properties of Franchaise that you want to edit
    public int Status { get; set; }
    public IEnumerable<SelectListItem> StatusList { get; set; }
    public IEnumerable<Franchaise> Franchaises { get; set; }
}

在视图的 GET 方法中

FranchaiseVM model = new FranchaiseVM()
{
    StatusList = new List<SelectListItem>()
    {
        new SelectListItem{ Text="Active", Value = "1" },
        new SelectListItem{ Text="Deactive", Value = "2" }
    },
    Franchaises = .... // your query for populating the collection
};
return View(model)

在主视图中

@model FranchaiseVM
....
@using (Html.BeginForm("Create", "Franchise", FormMethod.Post))
{
    .... your form controls
}
@{ Html.RenderAction("ListAllFranchise", "Franchise", Model.Franchisees); }

在 POST 方法中

[HttpPost]
public ActionResult Create(FranchaiseVM viewModel)
{
    if (!ModelState.IsValid)
    {
        model.StatusList = ... as per GET method
        model.Franchaises = ... as per GET method
       return View(viewModel);
    }
    // Initialize data model and set its properties
    Franchaise dataModel = new Franchaise()
    {
        Name = viewModel.Name,
        .... // map other properties
        Status = viewModel.Status, // not sure why you need to convert it
        StartDate = DateTime.Now;
    }
    _FranchaiseServices.Create(dataModel);
    return RedirectToAction("GetAll");
}

旁注:在这种情况下,似乎没有理由使用RenderAction() 来生成现有项目。更好的方法是在/Views/Shared/DisplayTemplates/Franchaise.cshtml 中创建DisplayTemplate

@model Franchaise
@Html.DisplayFor(m => m.Name)
....

在主视图中使用@Html.DisplayFor(m =&gt; m.Franchaises),它将为集合中的每个项目生成html。

【讨论】:

  • 忘了在答案中提到,在您尝试的第二个示例中没有得到验证的原因是因为您所做的只是生成Franchaise 的新实例,但它没有通过@987654336 @values/errors 所以ModelState 里面什么都没有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-22
  • 2011-01-28
  • 1970-01-01
相关资源
最近更新 更多