2010-03-29 64 views
3

我已經在處理包含下拉列表的表單時遇到了幾天的麻煩。我嘗試了迄今爲止所學到的一切,但沒有任何幫助。這是我的代碼:
ASP.NET MVC - 下拉列表帖子處理問題

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using CMS; 
using CMS.Model; 
using System.ComponentModel.DataAnnotations; 

namespace Portal.Models 
{ 
    public class ArticleDisplay 
    { 
     public ArticleDisplay() { } 


     public int CategoryID { set; get; } 
     public string CategoryTitle { set; get; } 

     public int ArticleID { set; get; } 
     public string ArticleTitle { set; get; } 
     public DateTime ArticleDate; 
     public string ArticleContent { set; get; } 

    } 

    public class HomePageViewModel 
    { 
     public HomePageViewModel(IEnumerable<ArticleDisplay> summaries, Article article) 
     { 
      this.ArticleSummaries = summaries; 
      this.NewArticle = article; 
     } 
     public IEnumerable<ArticleDisplay> ArticleSummaries { get; private set; } 
     public Article NewArticle { get; private set; } 
    } 


    public class ArticleRepository 
    { 
     private DB db = new DB(); 

     // 
     // Query Methods   

     public IQueryable<ArticleDisplay> FindAllArticles() 
     { 
      var result = from category in db.ArticleCategories 
         join article in db.Articles on category.CategoryID equals article.CategoryID 
         orderby article.Date descending 
         select new ArticleDisplay 
         { 
          CategoryID = category.CategoryID, 
          CategoryTitle = category.Title, 

          ArticleID = article.ArticleID, 
          ArticleTitle = article.Title, 
          ArticleDate = article.Date, 
          ArticleContent = article.Content 
         }; 

      return result; 

     } 

     public IQueryable<ArticleDisplay> FindTodayArticles() 
     { 
      var result = from category in db.ArticleCategories 
         join article in db.Articles on category.CategoryID equals article.CategoryID 
         where article.Date == DateTime.Today 
         select new ArticleDisplay 
         { 
          CategoryID = category.CategoryID, 
          CategoryTitle = category.Title, 

          ArticleID = article.ArticleID, 
          ArticleTitle = article.Title, 
          ArticleDate = article.Date, 
          ArticleContent = article.Content 
         }; 

      return result; 
     } 
     public Article GetArticle(int id) 
     { 
      return db.Articles.SingleOrDefault(d => d.ArticleID == id); 
     } 

     public IQueryable<ArticleDisplay> DetailsArticle(int id) 
     { 
      var result = from category in db.ArticleCategories 
         join article in db.Articles on category.CategoryID equals article.CategoryID 
         where id == article.ArticleID 
         select new ArticleDisplay 
         { 
          CategoryID = category.CategoryID, 
          CategoryTitle = category.Title, 

          ArticleID = article.ArticleID, 
          ArticleTitle = article.Title, 
          ArticleDate = article.Date, 
          ArticleContent = article.Content 
         }; 

      return result; 
     } 


     // 
     // Insert/Delete Methods 

     public void Add(Article article) 
     { 
      db.Articles.InsertOnSubmit(article); 
     } 

     public void Delete(Article article) 
     { 
      db.Articles.DeleteOnSubmit(article); 
     } 

     // 
     // Persistence 

     public void Save() 
     { 
      db.SubmitChanges(); 
     } 
    } 
} 



using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using Portal.Models; 
using CMS.Model; 

namespace Portal.Areas.CMS.Controllers 
{ 
    public class ArticleController : Controller 
    { 
     ArticleRepository articleRepository = new ArticleRepository(); 
     ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository(); 

     // 
     // GET: /Article/ 

     public ActionResult Index() 
     { 
      ViewData["categories"] = new SelectList 
      (
       articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" 
      ); 

      Article article = new Article() 
      { 
       Date = DateTime.Now, 
       CategoryID = 1 
      }; 

      HomePageViewModel homeData = new HomePageViewModel(articleRepository.FindAllArticles().ToList(), article); 

      return View(homeData);    
     } 

     // 
     // GET: /Article/Details/5 

     public ActionResult Details(int id) 
     { 
      var article = articleRepository.DetailsArticle(id).Single(); 

      if (article == null) 
       return View("NotFound"); 

      return View(article); 
     } 

     // 
     // GET: /Article/Create 

     //public ActionResult Create() 
     //{ 
     // ViewData["categories"] = new SelectList 
     // (
     //  articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" 
     // ); 

     // Article article = new Article() 
     // { 
     //  Date = DateTime.Now, 
     //  CategoryID = 1 
     // }; 

     // return View(article); 
     //} 

     // 
     // POST: /Article/Create 

     [ValidateInput(false)] 
     [AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Create(Article article) 
     { 
      if (ModelState.IsValid) 
      { 
       try 
       { 
        // TODO: Add insert logic here 

        articleRepository.Add(article); 
        articleRepository.Save(); 

        return RedirectToAction("Index"); 
       } 
       catch 
       { 
        return View(article); 
       } 
      } 
      else 
      { 
       return View(article); 
      } 
     } 

     // 
     // GET: /Article/Edit/5 

     public ActionResult Edit(int id) 
     { 
      ViewData["categories"] = new SelectList 
      (
       articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" 
      ); 

      var article = articleRepository.GetArticle(id); 

      return View(article); 
     } 

     // 
     // POST: /Article/Edit/5 

     [ValidateInput(false)] 
     [AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Edit(int id, FormCollection collection) 
     { 
      Article article = articleRepository.GetArticle(id); 

      try 
      { 
       // TODO: Add update logic here 
       UpdateModel(article, collection.ToValueProvider()); 
       articleRepository.Save(); 

       return RedirectToAction("Details", new { id = article.ArticleID }); 
      } 
      catch 
      { 
       return View(article); 
      } 
     } 

     // 
     // HTTP GET: /Article/Delete/1 
     public ActionResult Delete(int id) 
     { 
      Article article = articleRepository.GetArticle(id); 

      if (article == null) 
       return View("NotFound"); 

      else 
       return View(article); 
     } 

     // 
     // HTTP POST: /Article/Delete/1 
     [AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Delete(int id, string confirmButton) 
     { 
      Article article = articleRepository.GetArticle(id); 

      if (article == null) 
       return View("NotFound"); 

      articleRepository.Delete(article); 
      articleRepository.Save(); 

      return View("Deleted"); 
     } 

     [ValidateInput(false)] 
     public ActionResult UpdateSettings(int id, string value, string field) 
     { 
      // This highly-specific example is from the original coder's blog system, 
      // but you can substitute your own code here. I assume you can pick out 
      // which text field it is from the id. 

      Article article = articleRepository.GetArticle(id); 

      if (article == null) 
       return Content("Error"); 

      if (field == "Title") 
      { 
       article.Title = value; 
       UpdateModel(article, new[] { "Title" }); 
       articleRepository.Save(); 
      } 
      if (field == "Content") 
      { 
       article.Content = value; 
       UpdateModel(article, new[] { "Content" }); 
       articleRepository.Save(); 
      } 
      if (field == "Date") 
      { 
       article.Date = Convert.ToDateTime(value); 
       UpdateModel(article, new[] { "Date" }); 
       articleRepository.Save(); 
      } 

      return Content(value); 
     } 


    } 
} 

和看法:

<%@ Page Title="" Language="C#" MasterPageFile="~/Areas/CMS/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Portal.Models.HomePageViewModel>" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    Index 
</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

    <div class="naslov_poglavlja_main">Articles Administration</div> 

    <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> 

    <% using (Html.BeginForm("Create","Article")) {%> 

      <div class="news_forma"> 

       <label for="Title" class="news">Title:</label> 
       <%= Html.TextBox("Title", "", new { @class = "news" })%> 
       <%= Html.ValidationMessage("Title", "*") %> 

       <label for="Content" class="news">Content:</label> 
       <div class="textarea_okvir"> 

        <%= Html.TextArea("Content", "", new { @class = "news" })%> 
        <%= Html.ValidationMessage("Content", "*")%> 
       </div> 

       <label for="CategoryID" class="news">Category:</label> 
       <%= Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewData["categories"], new { @class = "news" })%> 

       <p> 
        <input type="submit" value="Publish" class="form_submit" /> 
       </p> 


      </div> 

    <% } %> 


    <div class="naslov_poglavlja_main"><%= Html.ActionLink("Write new article...", "Create") %></div> 

    <div id="articles"> 
     <% foreach (var item in Model.ArticleSummaries) { %> 

      <div>  
       <div class="naslov_vijesti" id="<%= item.ArticleID %>"><%= Html.Encode(item.ArticleTitle) %></div> 
       <div class="okvir_vijesti"> 

        <div class="sadrzaj_vijesti" id="<%= item.ArticleID %>"><%= item.ArticleContent %></div>  
        <div class="datum_vijesti" id="<%= item.ArticleID %>"><%= Html.Encode(String.Format("{0:g}", item.ArticleDate)) %></div> 

        <a class="news_delete" href="#" id="<%= item.ArticleID %>">Delete</a> 

       </div> 

       <div class="dno"></div> 
      </div> 

     <% } %> 
    </div> 

</asp:Content> 

當試圖發表新文章中,我得到以下錯誤:

System.InvalidOperationException: The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable'.

我真的不知道該怎麼辦因爲我很新.net和mvc

任何幫助讚賞!




編輯:

我發現,我犯的錯誤。我沒有包含日期​​。 如果考慮到我的形式加入這一行,我可以添加文章:

<%=Html.Hidden("Date", String.Format("{0:g}", Model.NewArticle.Date)) %> 

但是,如果我輸錯datetype或離開的標題和內容爲空,然後我得到了同樣的錯誤。在這個例子中,不需要日期編輯,但我需要它來處理其他一些表單,並且驗證將是必要的。



編輯2:發帖時 錯誤發生!
調用堆棧:
App_Web_of9beco9.dll ASP.areas_cms_views_article_create_aspx .__ RenderContent2(System.Web.UI.HtmlTextWriter __w = {} System.Web.UI.HtmlTextWriter,System.Web.UI.Control parameterContainer = {System.Web程序。 UI.WebControls.ContentPlaceHolder})線31 + 0x9f字節C#

回答

3

解決了! 問題在這裏:

public ActionResult Create() 
     { 
      ViewData["categories"] = new SelectList 
      (
       articleCategoryRepository.FindAllCategories().ToList(), "CategoryID", "Title" 
      ); 

      Article article = new Article() 
      { 
       Date = DateTime.Now, 
       CategoryID = 1 
      }; 

      return View(article); 
     } 

我設置類別ID是整數,這就是問題所在了。如果我刪除這條線,一切正常。但接下來的問題是如何在下拉列表中設置默認類別?

0

看是否有此修復它:

<label for="CategoryID" class="news">Category:</label> 
<%= Html.DropDownList("CategoryId", null, "-- Select Category --", new { @class = "news" })%> 

您可以發佈到底在哪錯誤被拋起來的景觀?這可能有助於我們更清楚地看待它。

+0

另外,你可以告訴你使用是否在頁面被渲染時或發佈回發時發生錯誤。 – Ashok 2010-03-29 12:35:22

+0

在下拉列表所在的視圖中精確發佈時發生錯誤。我編輯了我的問題。 – 2010-03-29 12:56:53

0

我有同樣的錯誤。最後它是沒有填充的Combobox。

我的解決方案是:我在Create Method(響應GET請求的那個)中填充了一個DropDownList,並將它傳遞給ViewData/ViewBag的View。

創建方法(用於POST請求)在調用dataContext時引發異常。調用SaveChanges()和卡也只包含這樣的:

catch 
     { 
      return View(companyRating); 
     } 

這還不夠,查看預期填充了一個ViewData.Ratings的SelectList至極wasnt。所以我把它改爲

catch (Exception ex) 
     { 
      // Errormessage for now, of course should be made user-friendly 
      ModelState.AddModelError("_FORM", ex.InnerException.Message); 

      string[] list = new string[] { "1", "2", "3", "4", "5" }; 
      SelectList ratings = new SelectList(list); 
      ViewBag.Ratings = ratings; 

      return View(companyRating); 
     }