具有'SelectedRating'键的ViewData项类型为 'System.Int32',但必须是'IEnumerable'类型的。MVC - DropDownList/PartialView问题 - “Viewdata有关键int .. ..必须是Iumeumerable ...”
这是我在尝试通过局部视图添加DropDownList时得到的错误。我试图遵循this solution,但由于我在编码方面的经验不足,我无法做到这一点。
这是我的代码看起来就目前如何:
[HttpGet]
public ActionResult Rating()
{
RateReviewVM model = new RateReviewVM()
{
ReviewId = id,
RatingList = new SelectList(Enumerable.Range(1, 10))
};
return View(model);
}
[HttpPost]
public ActionResult Rating(RateReviewVM model) {
if (!ModelState.IsValid)
{
model.RatingList = new SelectList(Enumerable.Range(1, 10));
return View(model);
}
//...
信息查看_RatingPartial
@model xxxx.ViewModel.RateReviewVM
<h6>Rate the review</h6>
using (Html.BeginForm()) {
<div class="form-group">
@Html.LabelFor(m => m.SelectedRating)
@Html.DropDownListFor(m => m.SelectedRating, Model.RatingList, "-Please select-", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.SelectedRating)
</div>
<button type="submit" class="btn btn-default submit">Rate</button>
}
}
这是我尝试显示_RatingPartial视图
@{
var newRating = new xxxx.ViewModel.RateReviewVM { ReviewId = Model.Id };
Html.RenderPartial("_RatingPartial", newRating);
}
型号
public class RateReviewVM {
public System.Guid Id { get; set; }
public System.Guid UserId { get; set; }
public System.Guid ReviewId { get; set; }
public bool HasLiked { get; set; }
public Nullable<int> Rating { get; set; }
public int SelectedRating { get; set; }
public IEnumerable<SelectListItem> RatingList { get; set; }
}
编辑:---
详细信息视图(主)
@model xxxx.Review
@{
ViewBag.Title = "Details";
}
@*@{
//var newRating = new xxxx.ViewModel.RateReviewVM { ReviewId = Model.Id };
@Html.RenderPartial("_RatingPartial", newRating)
}*@
<h2>Details</h2>
<div>
<h4>Review</h4>
<hr/>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Description)
</dt>
<dd>
@Html.DisplayFor(model => model.Description)
</dd>
@* and so on.. *@
</dl>
</div>
<p>
@Html.ActionLink("Back to List", "Index")
</p>
控制器的详细
public ActionResult Details(Guid? id) {
Review review = db.Reviews.Find(id);
return View(review);
}
模型评论详情
public System.Guid Id { get; set; }
public System.Guid CreatorUserId { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public System.DateTime CreatedDate { get; set; }
//etc - some irrelevant property
public virtual ICollection<RateReview> Users { get; set; }
你的'RenderPartial()'只是初始化'RateReviewVM'的一个新实例,并且你没有填充该实例的'RatingList'属性(它的'null',因此是例外)。你为什么使用'RenderPartial()'?主视图中的模型是什么? –
@StephenMuecke我认为这是适当的显示部分。我应该用什么来代替? – skylake
您的GET方法建议在主视图中的模型已经是'RateReviewVM',那么'RenderPartial()'的意义何在。只要将'_RatingPartial.cshtml'部分的代码移动到'Rating.cshtml'文件中,并删除'RenderPartial()' –