如何验证视图中的项目列表(类对象) [英] How To Validate list of items(class objects) in a view

查看:52
本文介绍了如何验证视图中的项目列表(类对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图看起来像



My View looks like

@model List<MusicBusinessLayer.Music>
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { }))
{
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Music</legend>
 
 
 @for (int i = 0; i < Model.Count();i++ )
        {
        
        <div style="float:left;">
         <div class="editor-label">
        @Html.LabelFor(model => Model[i].Music_Id)
      </div>
      <div class="editor-field">
        @Html.EditorFor(model => Model[i].Music_Id)
       @Html.ValidationMessageFor(model => Model[i].Music_Id)
       </div>
 
        <pre><div class="editor-label">
        @Html.LabelFor(model => Model[i].Song_Name)
          </div>
         <div class="editor-field">
           @Html.EditorFor(model => Model[i].Song_Name)
         @Html.ValidationMessageFor(model => Model[i].Song_Name)
         </div>
 
            <div class="editor-label">
         @Html.LabelFor(model => Model[i].Music_Director)
         </div>
          <div class="editor-field">
          @Html.EditorFor(model => Model[i].Music_Director)
          @Html.ValidationMessageFor(model => Model[i].Music_Director)
           </div>
 }
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
            
}





我的Music.Class如下所示







And My Music.Class is show below


public class Music
    {
        [Required]
        public int Music_Id{ get; set; }
        [Required]
        public string  Song_Name { get; set; }
        [Required]
        public string Music_Director { get; set; }

}







如何验证此音乐文件列表controller.Thanks提前阅读问题




How to validate this list of music files in controller.Thanks in advance for reading the question

推荐答案

检查以下内容是否在控制器中提供了足够的信息?



Does checking for the following provide enough information in your controller?

if (ModelState.IsValid)
{
    // Continue process
}
else
{
    // Handle errors
}


跟进以前的帖子,可能值得考虑拆分视图并创建操作。



查看您的原始帖子,很难看到您可能想要一次添加多个项目的场景(应用程序将如何知道您想要的项目数量)添加?)。



从模型类开始..

Following up on the previous posts, it might be worth thinking about splitting the view and create actions up.

Looking at your original post, it's difficult to see a scenario where you might want to add many items at once (how would the application know how many items you wanted to add?).

So starting with your model class..
namespace Sample.Models
{
    using System.ComponentModel.DataAnnotations;

    /// <summary>
    /// The Music class.
    /// </summary>
    public class Music
    {
        [Required]
        public int Music_Id { get; set; }

        [Required]
        public string Song_Name { get; set; }

        [Required]
        public string Music_Director { get; set; }
    }
}



..添加两个视图;索引(显示存储在数据源中的当前音乐文件列表):


..add in two views; Index (to display the current list of music files stored in your data source):

@model List<sample.models.music>

<h1>Music</h1>

<table>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @item.Music_Id
            </td>
            <td>
                @item.Song_Name
            </td>
            <td>
                @item.Music_Director
            </td>
        </tr>
    }
</table>

@Html.ActionLink("Add", "Create")



。 .and Create(允许定义新的音乐文件):


..and Create (to allow a new music file to be defined):

@model Sample.Models.Music

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { }))
{
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Music</legend>
        <div class="editor-label">
            @Html.LabelFor(model => Model.Music_Id)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.Music_Id)
            @Html.ValidationMessageFor(model => Model.Music_Id)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => Model.Song_Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.Song_Name)
            @Html.ValidationMessageFor(model => Model.Song_Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => Model.Music_Director)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.Music_Director)
            @Html.ValidationMessageFor(model => Model.Music_Director)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}



然后最后更新您的控制器以处理相应的操作:


Then finally update your controller to handle the appropriate actions:

namespace Sample.Controllers
{
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Sample.Models;

    /// <summary>
    /// The HomeController class.
    /// </summary>
    public class HomeController : Controller
    {
        /// <summary>
        /// Performs the Index action.
        /// </summary>
        /// <returns>The Index view with data.</returns>
        public ActionResult Index()
        {
            return View(GetData());
        }

        /// <summary>
        /// Performs the Create (GET) action.
        /// </summary>
        /// <returns>The Create view with initial data.</returns>
        [HttpGet]
        public ActionResult Create()
        {
            return View(new Music());
        }

        /// <summary>
        /// Performs the Create (POST) action.
        /// </summary>
        /// <returns>The Create view with validation information, or a redirect back to the Index view.</returns>
        [HttpPost]
        public ActionResult Create(Music model)
        {
            if (ModelState.IsValid)
            {
                AddItem(model);
                return RedirectToAction("Index");
            }

            return View(model);
        }

        /// <summary>
        /// Gets the simulated data source items.
        /// </summary>
        /// <returns>The simulated data source items.</returns>
        private List<music> GetData()
        {
            if (Session["data"] == null)
            {
                Session["data"] = new List<music>();
            }

            return (List<music>)Session["data"];
        }

        /// <summary>
        /// Adds a new item to the simulated data source.
        /// </summary>
        /// <param name="item">The item to add.</param>
        private void AddItem(Music item)
        {
            var data = GetData();
            data.Add(item);
            Session["data"] = data;
        }
    }
}



请注意,在我给出的示例中,我只是创建一个模拟数据源一个会话变量。



如果你真的想一次添加多个项目,你可以修改创建操作,只需在数据源中添加一个空白项目并更改添加POST索引操作,用于执行数据更新。如果您正在寻找,请告诉我,我会在此处发布该解决方案。


Note that in the example I've given, I'm just creating a simulated data source as a Session variable.

If you really wanted to add multiple items at once, you could modify the Create action to just add a blank item to your data source and change add a POST Index action to perform an Update on the data instead. Let me know if that's what you're looking for and I'll post that solution here.


这篇关于如何验证视图中的项目列表(类对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆