我在创建对象时遇到问题,但我不知道为什么。我在 Post Create 方法的参数中有空对象,在 ModelState 中出现此错误:
{System.InvalidOperationException:从类型“System.String”到类型“BlanskoMenu.Models.ActionOffer”的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。在 System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo 文化,对象值,类型 destinationType) 在 System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo 文化,对象值,类型 destinationType) 在 System.Web.Mvc.ValueProviderResult.ConvertTo (类型类型,CultureInfo 文化)在 System.Web.Mvc.DefaultModelBinder.ConvertProviderResult(ModelStateDictionary modelState, String modelStateKey, ValueProviderResult valueProviderResult, Type destinationType)}
这些是我在控制器中的方法:
//
// GET: /Action/
public ActionResult Index()
{
var offers = _repository.GetAllActionOffers();
return View(offers);
}
//
// GET: /Action/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Action/Create
[HttpPost]
public ActionResult Create(ActionOffer action)
{
try
{
if (ModelState.IsValid)
{
_repository.CreateActionOffer(action);
return RedirectToAction("Index");
}
return View(action);
}
catch
{
return View(action);
}
}
这是我的 ActionOffer 模型:
public class ActionOffer
{
[Key]
public int Id { get; set; }
public string Text { get; set; }
public string Title { get; set; }
public string ImagePath { get; set; }
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
}
这是我的创建视图:
@model BlanskoMenu.Models.ActionOffer
@{
ViewBag.Title = "Vytvořit akční nabídku";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Vytvořit akční nabídku</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Akční nabídka</legend>
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Text)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ImagePath)
@Html.ValidationMessageFor(model => model.ImagePath)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.StartDate)
@Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EndDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EndDate)
@Html.ValidationMessageFor(model => model.EndDate)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
感谢帮助