1

我创建了一个运行良好的视图,直到我添加了一些 JQuery 来支持级联下拉菜单。我相信这样做,我打破了视图和模型之间的绑定。我收到错误“没有为此对象定义无参数构造函数”。提交表单时。显而易见的解决方案是添加一个无参数构造函数,但我假设 postmodel 将为空?下面的代码片段。

在此先感谢您的帮助。

看法:

<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

1

我纠正了这个问题,并想分享一下,以防其他人像我一样用头撞到他们的桌子上。基本上我更改了下拉列表以反映:

@Html.DropDownListFor(model => model.iSubCategoryID, new SelectList(Enumerable.Empty<SelectListItem>(), "iSubCategoryID", "SubCategory",Model.SubCategories), "--Select SubCategory--", new Dictionary<string,object>{ {"class","dropdowns"},{"id","ddlSubCategory"},{"name","iSubCategoryID"}})
于 2013-04-09T11:36:46.420 回答
0

假设这里的问题出在您的 VendorCreateModel 中,您需要添加或删除无参数构造函数,然后在您的操作方法中创建一个实例并通过 TryUpdateModel 填充它。或者使用 FormsCollection 解析表单(不是粉丝)。

您没有在此处发布视图模型的代码,但基本假设是它会映射。

于 2013-04-05T20:21:23.900 回答