0

私がやろうとしているのは、SubCategory オブジェクトを作成することです。そのために、ビューに必要なデータ (サブカテゴリがバインドされるカテゴリ オブジェクトを含む) を提供するビューモデルを作成しました。

フォームを投稿すると、ビューモデルがコントローラーに返されますが、サブカテゴリのすべてのプロパティとドロップダウン リストから選択した値が null です。

私は何を間違っていますか?:S

見る:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.master" Inherits="System.Web.Mvc.ViewPage<SkyLearn.Areas.Categories.Models.CategoryViewModel>" %>

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

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

<h2>Create</h2>

<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>

<form action="" method="post" enctype="multipart/form-data">
    <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>SubCategory</legend>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.subcategory.Title) %>
        </div>
        <div class="editor-field">
            <%: Html.EditorFor(model => model.subcategory.Title)%>
            <%: Html.ValidationMessageFor(model => model.subcategory.Title)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.subcategory.Icon)%>
        </div>
        <div class="editor-field">
            <input type="file" name="icon" id="icon"/>
        </div>

        <%: Html.DropDownListFor(selectedcategory => Model.selectedCategory, Model.categories) %>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.subcategory.Description)%>
        </div>
        <div class="editor-field">
            <%: Html.EditorFor(model => model.subcategory.Description)%>
            <%: Html.ValidationMessageFor(model => model.subcategory.Description)%>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
</form>

<div>
    <%: Html.ActionLink("Back to List", "Index") %>
</div>

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="SideContent" runat="server">
</asp:Content>

コントローラ:

[Authorize(Roles = "administrator")]
        [HttpPost]
        public ActionResult Create(CategoryViewModel viewmodel, HttpPostedFileBase Icon)
        {
            SubCategory subcategory = viewmodel.subcategory;

            subcategory.Category = categorycontroller.getCategoryByName(viewmodel.selectedCategory);

            if (Icon != null && Icon.ContentLength > 0)
            {
                // extract only the filename
                var fileName = Path.GetFileName(Icon.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("../../Content/icons/"), fileName);
                Icon.SaveAs(path);
                subcategory.Icon = fileName;
            }

            if (ModelState.IsValid)
            {
                db.subcategories.Add(subcategory);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(subcategory);
        }

ビューモデル:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;

namespace SkyLearn.Areas.Categories.Models
{
    public class CategoryViewModel
    {
        public List<SelectListItem> categories;
        public SubCategory subcategory;
        public string selectedCategory;

        public CategoryViewModel()
        {
            categories = new List<SelectListItem>();
            subcategory = new SubCategory();
            selectedCategory = "";
        }
    }
}

ビューモデルには、作成しようとしているサブカテゴリがバインドできるカテゴリのリストが含まれています。また、サブカテゴリを作成するために使用できるサブカテゴリ オブジェクトも含まれています。最後のプロパティは、ドロップダウンリストで選択をバインドするために使用したい文字列です。

4

1 に答える 1

1

ASP.Net MVC3 の SelectListItem は、期待どおりに動作しません。また、Html.EditorFor() ではなく Html.DropDownListFor() を試して、ドロップダウン リストを作成してください。

ビューモデルで:

public IList<string> PossibleValues {get; set;}
public string SelectedValue {get; set;}

ViewModel のコンストラクターで、PossibleValues に値を読み込みます。

ビューで:

@Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.PossibleValues))

これにより、ドロップダウン リストが自動生成され、モデルにバインドされます。必要に応じて、デフォルト値やその他のカスタマイズをこの Html ヘルパー関数に渡すこともできます。

他の値 を保存する ユーザーが編集するオプションを持つべきではないが、ユーザーが編集した場合にミッション クリティカルではない他の値を保存することができます。

@Html.HiddenFor(m => m.RememberThisValue);

この値は表示されませんが、DOM で編集したり、ユーザーが望むものを投稿したりできることに注意してください。POST された非表示の値をチェックして、悪意のある値の挿入から身を守ってください。

重要なものはすべてサーバー側に保存し、モデルを介してユーザーにハッシュ/秘密鍵を渡し、静的セッション ディクショナリを実装してこれらの小さな情報を保存します。

于 2012-04-30T14:29:52.417 に答える