传递数据以供编辑查看时出错

时间:2011-12-31 09:25:41

标签: asp.net-mvc asp.net-mvc-3

我正在尝试传递模型类的对象以进行编辑但是接收此错误“传递到字典中的模型项的类型为'System.Collections.Generic.List`1 [MvcApplication1.Models.ResturantReviews] ',但是这个字典需要一个'MvcApplication1.Models.ResturantReviews'类型的模型项。“

请指导我错在哪里,这是我的代码:

我的模特课程:

namespace MvcApplication1.Models{
public class ResturantReviews
{

        public int ReviewId { get; set; }
        public int Rating { get; set; }
        public string ReviewBody { get; set; }
        public Resturant Resturant { get; set; }

}

}

我的行动代码:

public ActionResult Edit(int Id)
    {
        //var review = FoodDB.review;
        ResturantReviews obj = new ResturantReviews {
          ReviewId = 2,
            Rating = 9,
            ReviewBody = "Test Sarina is a good resturant for continantal food",
            Resturant = new Resturant
            {
                ResturantId = 1,
                ResturantAddress = "Commercial area",
                ResturantName = "Sarina Hotel"

            }
        };



        return View(obj);
    }

我在视图中的代码:

@model MvcApplication1.Models.ResturantReviews

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ResturantReviews</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.ReviewId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ReviewId)
            @Html.ValidationMessageFor(model => model.ReviewId)
        </div>

        <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.ReviewBody)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ReviewBody)
            @Html.ValidationMessageFor(model => model.ReviewBody)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

1 个答案:

答案 0 :(得分:4)

编辑控制器操作(如您的问题所示)传递ResturantReviews的单个实例,并且视图强类型为@model ResturantReviews,因此不应抛出异常。代码看起来是正确的。

所以你可以尝试通过最大限度地简化来缩小范围:

public ActionResult Edit(int Id)
{
    var model = new ResturantReviews();
    return View(model);
}

Edit.cshtml视图:

@model ResturantReviews
@Html.BeginForm()
{
    <p>
        <input type="submit" value="Save" />
    </p>    
}

这应该100%有效。然后你就可以开始添加功能了。