代码之家  ›  专栏  ›  技术社区  ›  Peter

MVC创建包含联系人数据的艺术家

  •  0
  • Peter  · 技术社区  · 15 年前

    我对MVC框架还比较陌生,在过去的几天/晚上我都在学习这些教程。 我有一个与服务和提供者松散耦合的设计,并且正在使用实体框架。我正在使用所有最新的软件,Visual Studio 2008,.NET 3.5 Framework,MVC,Entity Framework。

    我正在尝试创建一个视图艺术家/创建,用户必须在其中输入所有艺术家和所有联系人字段。以下是我的资料:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    using System.Text.RegularExpressions;
    using Website.Models;
    using Website.Models.Validation;
    using Website.Models.Services;
    
    namespace Website.Controllers
    {
    public class ArtistController : Controller
    {
        private IArtistService _service;
        private ModelStateWrapper _msw;
    
        public ArtistController()
        {
            _msw = new ModelStateWrapper(this.ModelState);
            _service = new ArtistService(_msw);
        }
    
        public ArtistController(IArtistService service)
        {
            _service = service;
        }
    
        //
        // GET: /Artist/
    
        public ActionResult Index()
        {
            return View(_service.ListArtists());
        }
    
        public ActionResult Create()
        {
            ViewData["Countries"] = new SelectList(new CountryService(_msw).ListCountries().OrderBy(c => c.Name),"ID","Name");
            return View();
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude = "Id")] Artist artist)
        {
            ViewData["Countries"] = new SelectList(new CountryService(_msw).ListCountries().OrderBy(c => c.Name), "ID", "Name");
            if (_service.CreateArtist(artist))
                return RedirectToAction("Index");
            return View("Create");
        }
    
        public ActionResult Edit(string name)
        {
            return View(_service.GetArtist(name));
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Artist artistToEdit)
        {
            if (_service.EditArtist(artistToEdit))
                return RedirectToAction("Index");
            return View();
        }
    
        public ActionResult Delete(string name)
        {
            return View(_service.GetArtist(name));
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(Artist artistToDelete)
        {
            if (_service.DeleteArtist(artistToDelete))
                return RedirectToAction("Index");
            return View();
        }
    }
    }
    

    这是view artist/create.aspx

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
       <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
        <title>Artist</title>
        <link href="../../Content/ui-lightness/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" media="screen" />
        <script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        <script src="../../Scripts/ui.core.js" type="text/javascript"></script>
        <script src="../../Scripts/ui.datepicker.js" type="text/javascript"></script>
        <script src="../../Scripts/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script>
        <script src="../../Scripts/ui.qtips.js" type="text/javascript"></script>
       </asp:Content>
       <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Create Artist</h2>
    <%= Html.ValidationSummary() %>
    
    <% using (Html.BeginForm()) {%>
    
        <fieldset class="fields">
            <legend>Create New Artist</legend>
            <p>
                <label for="Name">Name:</label>
                <%= Html.TextBox("Name", "", new { watermark = "Name", title = "Please enter your Artist name." })%>
                <%= Html.ValidationMessage("Name", "*") %>
            </p>
    
            <fieldset class="fields">
                <legend>Contact Information</legend>
                <p>
                    <label for="FirstName">First Name:</label>
                    <%= Html.TextBox("FirstName", "", new { watermark = "FirstName", title = "Please enter your first name." }) %>
                    <%= Html.ValidationMessage("FirstName", "*") %>
                </p>
                <p>
                    <label for="LastName">Last Name:</label>
                    <%= Html.TextBox("LastName", "", new { watermark = "Lastname", title = "Please enter your last name." })%>
                    <%= Html.ValidationMessage("LastName", "*") %>
                </p>
                <p>
                    <label for="Phone">Phone:</label>
                    <%= Html.TextBox("Phone", "", new { watermark = "+12 123 123456", title = "Please enter your phone number." })%>
                    <%= Html.ValidationMessage("Phone", "*") %>
                </p>
                <p>
                    <label for="Email">Email:</label>
                    <%= Html.TextBox("Email", "", new { watermark = "example@musicflock.com", title = "Please enter your email address." })%>
                    <%= Html.ValidationMessage("Email", "*") %>
                </p>
                <p>
                    <label for="BirthDate">Date of Birth:</label> 
                    <%= Html.TextBox("Birthdate", "", new { Class = "date-pick", watermark = "mm/dd/yyyy", title = "Please select your date of birth." })%> 
                    <%= Html.ValidationMessage("Birthdate", "*") %>
                </p>
                <p>
                    <label for="AddressLine1">Address:</label>
                    <%= Html.TextBox("AddressLine1", "", new { watermark = "", title = "Please enter your address." })%>
                    <%= Html.ValidationMessage("AddressLine1", "*") %>
                </p>
                <p>
                    <label for="AddressLine2"></label>
                    <%= Html.TextBox("AddressLine2", "", new { watermark = "First", title = "Optional additional addressline." })%>
                    <%= Html.ValidationMessage("AddressLine2", "*") %>
                </p>
                <p>
                    <label for="Country">Country:</label>
                    <%= Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewData["Countries"],string.Empty, new { watermark = "First", title = "Please enter your email address." })%>
                    <%= Html.ValidationMessage("City", "*") %>
                </p>
                <p>
                    <label for="City">City:</label>
                    <%= Html.TextBox("City", "", new { watermark = "", title = "Please specify your City.", @class="tooltip" })%>
                    <%= Html.ValidationMessage("City", "*") %>
                </p>
                <p>
                    <label for="ZipCode">ZipCode:</label>
                    <%= Html.TextBox("ZipCode", "", new { watermark = "", title = "Please specify your Zipcode." })%>
                    <%= Html.ValidationMessage("ZipCode", "*") %>
                </p>
                <fieldset class="fields">
                    <legend>Sex/Gender</legend>
                    <label for="SexMale">Male</label>
                    <%= Html.RadioButton("Sex", "Male", new { @id = "Sex.Male" })%>
                    <label for="SexFemale">Female</label>
                    <%= Html.RadioButton("Sex", "Female", new { @id = "Sex.Female" })%>
                    <%= Html.ValidationMessage("Sex", "*") %>
                </fieldset>
    
            </fieldset>
            <p class="submit">
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    
    <% } %>
    <!-- jquery plugins -->
    <script type="text/javascript">
        $(function() {
           $('.date-pick').datepicker({
               changeMonth: true,
               changeYear: true,
               yearRange: '1900:' + (new Date()).getFullYear()
           });
           $('.tooltip').qtip({ content: 'this is a nice tooltip', position: 'center' });
       });
    </script>
    <!-- /jquery plugins -->
    </asp:Content>
    

    我可以打开这个页面并输入所有数据。以下是我尝试使用ArtistService(这是出错的地方)来拯救艺术家的地方:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Text.RegularExpressions;
    using Website.Models.Repositories;
    using Website.Models.Validation;
    
    namespace Website.Models.Services
    {
        public class ArtistService : IArtistService
        {
            private IValidationDictionary _validationDictionary;
            private IArtistRepository _repository;
    
            public ArtistService(IValidationDictionary validationDictionary) 
                : this(validationDictionary, new EntityArtistRepository()){}
    
            public ArtistService(IValidationDictionary validationDictionary, IArtistRepository repository)
            {
                _validationDictionary = validationDictionary;
                _repository = repository;
            }
    
            public bool ValidateArtist(Artist artist)
            {
                ContactService contactService = new ContactService(_validationDictionary);
                if (contactService.ValidateContact(artist.Contact))
                    _validationDictionary.AddError("Contact", "Invalid Contact information.");
    
                if (_validationDictionary.IsValid)
                {
                    CountryService countryService = new CountryService(_validationDictionary);
                    if (artist.Contact.Country != null && countryService.ValidateCountry(artist.Contact.Country))
                        _validationDictionary.AddError("Country", "Country is required.");
                }
    
                if (artist.Name == null || artist.Name.Trim().Length == 0) {
                    _validationDictionary.AddError("Name", "Artist name is required.");
                }
    
                return _validationDictionary.IsValid;
            }
    
            #region IArtistService Members
    
            public bool CreateArtist(Artist artist)
            {
                // Validation logic
                if (!ValidateArtist(artist))
                    return false;
    
                // Database logic
                try
                {
                    _repository.CreateArtist(artist);
                }
                catch
                {
                    return false;
                }
                return true;
            }
    
            public bool EditArtist(Artist artist)
            {
                // Validation logic
                if (!ValidateArtist(artist))
                    return false;
    
                // Database logic
                try
                {
                    _repository.EditArtist(artist);
                }
                catch
                {
                    return false;
                }
                return true;
            }
    
            public Artist GetArtist(int Id)
            {
                return _repository.GetArtist(Id);
            }
    
            public bool DeleteArtist(Artist artist)
            {
                try
                {
                    _repository.DeleteArtist(artist);
                }
                catch
                {
                    return false;
                }
                return true;
            }
    
            public IEnumerable<Artist> ListArtists()
            {
                return _repository.ListArtists();
            }
    
            public Artist GetArtist(string name)
            {
                return _repository.GetArtist(name);
            }
    
            #endregion
        }
    }
    

    有人能告诉我为什么每次在validateArtist中,艺术家实体的contact属性都是空的吗?如何告诉MVC它应该将联系人输入字段链接到艺术家实体的联系人属性?

    我希望我把所有的代码都贴在这里没关系,看起来像很多…

    谢谢, 彼得

    1 回复  |  直到 15 年前
        1
  •  1
  •   tvanfosson    15 年前

    实际上,您创建了两个模型。尝试在“联系人”字段中预先设置联系人指示符。

          <p>
                <label for="Contact_Phone">Phone:</label>
                <%= Html.TextBox("Contact.Phone", "", new { watermark = "+12 123 123456", title = "Please enter your phone number." })%>
                <%= Html.ValidationMessage("Contact.Phone", "*") %>
         </p>
    

    然后,如果它不填充操作中的联系人字段,请尝试向操作方法添加联系人参数,并从中设置艺术家的联系人属性。

    public ActionResult Create([Bind(Exclude = "Id")] Artist artist,
                               [Bind(Prefix = "Contact")] Contact contact )
    {
        artist.Contact = contact;
        ...
    }