1

カスケード ドロップ ダウンをサポートするためにいくつかの JQuery を追加するまでは、素晴らしく機能するビューを作成しました。私はそれを行うことを信じて、ビューとモデルの間のバインディングを壊しました。「このオブジェクトにパラメーターなしのコンストラクターが定義されていません」というエラーが表示されます。フォームが送信されたとき。明らかな解決策は、パラメーターなしのコンストラクターを追加することですが、ポストモデルが null になると想定していますか? 以下のコード スニペット。

ご協力いただきありがとうございます。

意見:

<script type="text/javascript">
$(document).ready(function () {
      $("#ddlCategories").change(function () {
        var iCategoryId = $(this).val();
            $.getJSON(
                 "@Url.Content("~/Remote/SubCategoriesByCateogry")",
                { id: iCategoryId },
                function (data) {
                    var select = ResetAndReturnSubCategoryDDL();
                    $.each(data, function (index, itemData) {
                        select.append($('<option/>', { value: itemData.Value, text: itemData.Text }));
                    });
                });
        });
    function ResetAndReturnSubCategoryDDL() {
        var select = $('#ddlSubCategory');
        select.empty();
        select.append($('<option/>', { value: '', text: "--Select SubCategory--" }));
        return select;
    }
});

...

 <div class="editor-field">
            @Html.DropDownList("iCategoryID", Model.Categories,"--Select Category--", new Dictionary<string,object>{ {"class","dropdowns"},{"id","ddlCategories"}})
            @Html.ValidationMessage("iCategoryID")
        </div>
        <div class="editor-label">
           @Html.LabelFor(model => model.SubCategories, "SubCategory")
        </div>
        <div class="editor-field">
              @Html.DropDownListFor(model => model.SubCategories, new SelectList(Enumerable.Empty<SelectListItem>(), "iSubCategoryID", "SubCategory",Model.SubCategories), "--Select SubCategory--", new { id = "ddlSubCategory" })
              @Html.ValidationMessage("iSubCategoryID")
        </div>

コントローラ:

 [HttpPost]
     public ActionResult Create(VendorCreateModel postModel)
    {
        VendorCreateEditPostValidator createValidator = new VendorCreateEditPostValidator(
            postModel.iCategoryID,
            postModel.iSubCategoryID,
            postModel.AppliedPrograms,
            m_unitOfWork.ProgramRepository,
            new ModelStateValidationWrapper(ModelState));

        if (ModelState.IsValid)
        {
            int categoryId = int.Parse(postModel.iCategoryID);
            int subcategoryId = int.Parse(postModel.iSubCategoryID);
            var programIds = postModel.AppliedPrograms.Select(ap => int.Parse(ap));
            var programs = m_unitOfWork.ProgramRepository.GetPrograms(programIds);

            Vendor vendor = postModel.Vendor;
            vendor.Category = m_unitOfWork.CategoryRepository.GetCategory(categoryId);
            vendor.SubCategory = m_unitOfWork.SubCategoryRepository.GetSubCategory(subcategoryId);

            foreach (Program p in programs)
                vendor.Programs.Add(p);

            m_unitOfWork.VendorRepository.Add(vendor);
            m_unitOfWork.SaveChanges();

            return RedirectToAction("Index");  
        }

        VendorCreateModel model = new VendorCreateModel(
            postModel.Vendor,
            postModel.iCategoryID,
            postModel.iSubCategoryID,
            postModel.AppliedPrograms,
            User.Identity.Name,
            m_unitOfWork.CategoryRepository,
            m_unitOfWork.SubCategoryRepository,
            m_unitOfWork.PermissionRepository);

        return View(model);
    }

リモコン:

 [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult SubCategoriesByCateogry(int id)
    {
        System.Diagnostics.Debug.WriteLine(id);

        var SubCategories = db.SubCategories
            .Where(v => v.iCategoryID == id)
            .OrderBy(v => v.sDesc)
            .ToList();

        var modelData = SubCategories.Select(v => new SelectListItem()
        {
            Text = v.sDesc,
            Value = v.iSubCategoryID.ToString()
        });

        return Json(modelData, JsonRequestBehavior.AllowGet);
    }

ベンダー作成モデル:

public class VendorCreateModel
{
    public VendorCreateModel()
    {

    }

    public VendorCreateModel(
        Vendor vendor, 
        string categoryId,
        string subcategoryId,
        IEnumerable<string> appliedPrograms, 
        string username,
        ICategoryRepository categoryRepository,
        ISubCategoryRepository subcategoryRepository,
        IPermissionRepository permissionRepository)
    {
        UserHasProgramsValidator programValidator = new UserHasProgramsValidator(username, permissionRepository);
        var availablePrograms = programValidator.AvailablePrograms;

        HashSet<Category> applicableCategories = new HashSet<Category>();
        foreach (var p in availablePrograms)
            foreach (var c in categoryRepository.GetCategoriesByProgram(p.iProgramID))
                applicableCategories.Add(c);

        this.Vendor = vendor;
        this.AppliedPrograms = appliedPrograms;
        this.Categories = new SelectList(applicableCategories.OrderBy(x => x.sDesc).ToList(), "iCategoryID", "sDesc");
        this.SubCategories = new SelectList(subcategoryRepository.GetAllSubCategories().OrderBy(x => x.sDesc).ToList(), "iSubCategoryID", "sDesc");

        if (!string.IsNullOrEmpty(categoryId))
        {
            int temp;
            if (!int.TryParse(categoryId, out temp))
                throw new ApplicationException("Invalid Category Identifier.");
        }

        this.iCategoryID = categoryId;
        this.iSubCategoryID = subcategoryId;
        this.ProgramItems = availablePrograms
            .Select(p => new SelectListItem()
            {
                Text = p.sDesc,
                Value = p.iProgramID.ToString(),
                Selected = (AppliedPrograms != null ? AppliedPrograms.Contains(p.iProgramID.ToString()) : false)
            });
    }

    public Vendor Vendor { get; set; }
    public SelectList Categories { get; set; }
    public SelectList SubCategories { get; set; }
    public string iCategoryID { get; set; }
    public string iSubCategoryID { get; set; }
    public IEnumerable<SelectListItem> ProgramItems { get; set; }

    [AtLeastOneElementExists(ErrorMessage = "Please select at least one program.")]
    public IEnumerable<string> AppliedPrograms { get; set; }
}
4

2 に答える 2

0

ここで問題が VendorCreateModel にあると仮定すると、パラメーターなしのコンストラクターを追加するか、それを削除して、アクション メソッドでインスタンスを作成し、TryUpdateModel によって設定する必要があります。または、FormsCollection を使用してフォームを解析します (ファンではありません)。

ここに投稿されたビューモデルのコードはありませんが、基本的な前提は、それがマップされることです。

于 2013-04-05T20:21:23.900 に答える