我目前有一个包含两个文本框的视图,用户可以在其中输入一些数据。一个文本框只允许 1-10 的值,另一个是字符串。我不确定我做了什么代码更改,但接受字符串的第二个文本框不再“有效”。例如,当我输入一个字符串并尝试提交表单时,我收到一条验证消息,指出“值“(字符串)”无效。下面是我的解决方案中的一些代码片段。
实体:
public class MovieReview
{
public int Id { get; set; }
[Range(1, 10)]
[Required]
public int Rating { get; set; }
public string Review { get; set; }
public int MovieId { get; set; }
}
控制器:
public class ReviewsController : Controller
{
private MovieLoversDb _db = new MovieLoversDb();
public ActionResult Index([Bind(Prefix = "id")]int movieId)
{
var movie = _db.Movies.Find(movieId);
if (movie != null)
{
return View(movie);
}
return HttpNotFound();
}
[HttpGet]
public ActionResult Create(int movieId)
{
return View();
}
[HttpPost]
public ActionResult Create(MovieReview review)
{
if (ModelState.IsValid)
{
_db.MovieReviews.Add(review);
_db.SaveChanges();
return RedirectToAction("Index", new { id = review.MovieId });
}
return View(review);
}
局部视图:
@model MovieLovers.Models.MovieReview
@{
ViewBag.Title = "Review a Movie";
}
<h2>Review a Movie</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>New Review</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rating)
@Html.ValidationMessageFor(model => model.Rating)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Review)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Review)
@Html.ValidationMessageFor(model => model.Review)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ReviewerName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ReviewerName)
@Html.ValidationMessageFor(model => model.ReviewerName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
现在的问题是,我做错了什么?为什么会产生验证错误?