HTTP POST上的模型为空

时间:2015-04-24 06:01:27

标签: c# asp.net-mvc razor http-post

控制器

[HttpPost]
public ActionResult SaveProduct(string id, AddProductViewModel m)
{
    if (ModelState.IsValid)
    {
        using (ComparisonDBDataContext CMP = new ComparisonDBDataContext())
        {
            tblProduct prod = (from c in CMP.tblProducts
                               where c.ProductID == Guid.Parse(id)
                               select c).SingleOrDefault();
            prod.Name = m.myName;
            prod.CategoryID = Guid.Parse(m.myCategory);
            prod.ManufacturerID=Guid.Parse(m.myManufacturer);
            CMP.SubmitChanges();
        }
        return RedirectToAction("Products");
    }
    else
    {
        m.ProductID = Guid.Parse(id);
        return View("EditProduct", m);
    }
}

查看

@model Comparison.Models.AddProductViewModel 
@{
    ViewBag.Title = "EditProduct";
    Layout = "~/Views/_LayoutData.cshtml";
}

<style>
    .field-validation-error {
        color: Black;
    }
    .validation-summary-errors {
        font-weight: bold;
        color: Black;
    }
</style>
<h2>Edit Product</h2>
@using (Html.BeginForm("SaveProduct", "Home", new { id = @Model.ProductID }, FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true)
        <div class="form-group">
            <label class="control-label col-md-2" id="lblName">Name</label>
            <div class="col-md-5">
                @Html.TextBoxFor(m => m.myName, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.myName)
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-2" id="lblCategory">Category</label>
            <div class="col-md-5">
                @Html.DropDownListFor(m => m.myCategory,  Model.Category, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.myCategory)
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-2" id="lblManufucturer">Manufucturer</label>
            <div class="col-md-5">
                @Html.DropDownListFor(m => m.myManufacturer, Model.Manufacturer, new {@class="form-control" })
                @Html.ValidationMessageFor(m => m.myManufacturer)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Products")
</div>

查看模型

public Guid? myUserID;

        [Required(ErrorMessage="Required")]
        public string myCategory;
        public List<SelectListItem> category = new List<SelectListItem>();
        public List<SelectListItem> Category
        {
            get
            {

                category.Clear();
                using (ComparisonDBDataContext CMP = new ComparisonDBDataContext())
                {
                    var cat = from g in CMP.tblCategories
                              select new { g.Name, g.CategoryID };
                    foreach (var q in cat)
                    {
                        category.Add(new SelectListItem() { Text = q.Name, Value = q.CategoryID.ToString() });
                    }
                    return category;
                }
            }
        }
        public Guid? ProductID;

        [Required(ErrorMessage = "Required")]
        public string myManufacturer;
        public List<SelectListItem> manufacturer = new List<SelectListItem>();
        public List<SelectListItem> Manufacturer
        {
            get
            {

                category.Clear();
                using (ComparisonDBDataContext CMP = new ComparisonDBDataContext())
                {
                    var manu = from g in CMP.tblManufacturers
                              select new { g.Name, g.ManufacturerID };
                    foreach (var q in manu)
                    {
                        manufacturer.Add(new SelectListItem() { Text = q.Name, Value = q.ManufacturerID.ToString() });
                    }
                    return manufacturer;
                }
            }
        }

        [Required(ErrorMessage = "Required")]
        [StringLength(100, ErrorMessage = "Maximum lenght can be 100")]
        public string myName;

        public DateTime? CreationDate;

我尝试使用谷歌搜索但找不到任何解决方案。

我知道已经问过类似的问题,但我找不到他的解决方案。所以请仔细检查我的代码并告诉我我做错了什么。为什么我的模型在POSTBACK时为空?

1 个答案:

答案 0 :(得分:4)

您的视图模型包含仅包含getter的属性(在某些情况下,它们只是没有任何getter或setter的字段),因此DefaultModelBinder无法设置其值。它必须是

public string myName { get; set; }

附注:视图模型不应包含数据库访问代码。应该简单地

public List<SelectListItem> manufacturer { get; set; }

并且控制器应负责将集合分配给属性。