我使用表单中的数据在数据库中保存产品。如果任何所需输入为空,则验证如此 - >它返回带有错误语句的相同View。当我调试代码时,一切都很好,除了从下拉列表中选择的类别。它抛出一个null异常。
当我填写所有内容时,该类别获得了价值,我可以毫无问题地提交产品。如果其他一些输入为null,则ModelState设置为false,类别不会获得其值。
ADD行动
[HttpPost]
[Authorize(Roles = "prodejce")]
public ActionResult Add(Ski ski, HttpPostedFileBase picture, int categoryId)
{
try
{
if (ModelState.IsValid)
{
if (picture != null)
{
if (picture.ContentType == "image/jpeg" || picture.ContentType == "image/png")
{
Image image = Image.FromStream(picture.InputStream);
if (image.Height > 200 || image.Width > 200)
{
Image smallImage = ImageHelper.ScaleImage(image, 100, 100);
Bitmap b = new Bitmap(smallImage);
Guid guid = Guid.NewGuid();
string imageName = guid.ToString() + ".jpeg";
b.Save(Server.MapPath("~/uploads/Ski/" + imageName), ImageFormat.Jpeg);
smallImage.Dispose();
b.Dispose();
ski.ImageName = imageName;
}
else
{
picture.SaveAs(Server.MapPath("~/uploads/Ski/" + picture.FileName));
}
}
}
SkiCategoryDao skiCategoryDao = new SkiCategoryDao();
SkiCategory skiCategory = skiCategoryDao.GetById(categoryId);
ski.Category = skiCategory;
SkiDao skiDao = new SkiDao();
skiDao.Create(ski);
TempData["message-success"] = "Lyže byly úspěšně zadané";
}
else
{
return View("Create", ski); // this throws a new view
}
}
该部分视图效果正常
@model DataAccess.Model.Ski
@{
ViewBag.Title = "Create";
}
<h2>Nové lyže</h2>
@using (Html.BeginForm("Add", "Skies", FormMethod.Post, new { @class = "form-horizontal", enctype="multipart/form-data" }))
{
<div class="form-group">
<label class="col-sm-1 control-label">Délka</label>
<div class="col-sm-10">
@Html.TextBoxFor(x => x.Length, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Length)
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label">Značka</label>
<div class="col-sm-10">
@Html.TextBoxFor(x => x.Brand, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Brand)
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label">Popis</label>
<div class="col-sm-10">
@Html.TextAreaFor(x => x.Description, new { @class = "form-control formatedtext" })
@Html.ValidationMessageFor(x => x.Brand)
</div>
</div>
以下是空例外
<div class="form-group">
<label class="col-sm-1 control-label">Kategorie</label>
<div class="col-sm-10">
@Html.DropDownList("categoryId", new SelectList(ViewBag.Categories, "Id", "Name"), new { @class = "form-control" })
</div>
</div>