将模型数据从视图传递到控制器会导致错误

本文关键字:控制器 错误 数据 模型 视图 | 更新日期: 2023-09-27 18:14:30

我是MVC 4新手。

我收到以下错误:

Object reference not set to an instance of an object. Line 47:@Html.ActionLink("Back to List", "Index", new { id = Model.RestaurantId })

下面是导致错误的视图(请参阅最后几行):

@model OdeToFood.Models.RestaurantReview
@{
    ViewBag.Title = "Create";
}
<h2>Create</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.Body)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Body)
            @Html.ValidationMessageFor(model => model.Body)
        </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>
}
<div>
    @Html.ActionLink("Back to List", "Index", new { id = Model.RestaurantId })
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这是当Back To List链接被点击时被调用的控制器动作:

public ActionResult Index([Bind(Prefix="id")]int restaurantId)
{
    var restaurant = _db.Restaurants.Find(restaurantId);
    if (restaurant != null) {
        return View(restaurant);
    }
    return HttpNotFound(); 
}

下面是视图中强类型的RestaurantReview模型:

public class RestaurantReview
{
    public int Id { get; set; }
    public int Rating { get; set; }
    public string Body { get; set; }
    public string ReviewerName { get; set; }
    public int RestaurantId { get; set; }
}

任何帮助都将非常感激。

干杯!

将模型数据从视图传递到控制器会导致错误

在您的代码中,您正在显示Create视图和Index控制器。检查Create控制器是否通过Model,或者检查是否需要模型