MVC 3将View从View传递给Controller

时间:2013-03-25 04:09:16

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

每当我尝试使用模型将视图中的值传递给控制器​​时,它在控制器中显示为null。我在项目的另一部分尝试了非常相似的东西并没有遇到这个问题。为什么这会回来?

以下是控制器的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MovieProject2.Models;

namespace MovieProject2.Controllers
{

public class ReviewsController : Controller
{
public ActionResult Edit(int id = -1)
{
    if (id < 0)
    return HttpNotFound();
    MovieReview review = MovieADO.getReviewByID(id);
    return View(review);
}

[HttpPost]
public ActionResult Edit(MovieReview review)
{
    if (review == null) return HttpNotFound();
    return View(review);
}
}

查看:

@model MovieProject2.Models.MovieReview

@{
    ViewBag.Title = "Edit Review";
}

@{  //Not null here
    if(@Model != null) {<h2>Edit Review for @Model.MovieReviewed.Title</h2>
    <h4>Reviewed by @Model.Reviewer.Username</h4>}
                                                 else{<h2>Not Found</h2>
}
}

@using (Html.BeginForm())
{
    Html.ValidationSummary(true);
    <fieldset>
        <div class="editor-label">
            @Html.LabelFor(itemModel => Model.Rating)
        </div>
        <div class="editor-label">
            @Html.EditorFor(itemModel => Model.Rating)
            @Html.ValidationMessageFor(itemModel => Model.Rating)
        </div>
        <div class="editor-label">
            @Html.LabelFor(itemModel => Model.Review)
        </div>
        <div class="editor-label">
            @Html.EditorFor(itemModel => Model.Review)
            @Html.ValidationMessageFor(itemModel => Model.Review)
        </div>
        <p>
            <input type="submit" value="Change" />
        </p>
    </fieldset> 

}

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MovieProject2.Models
{
    public class MovieReview
    {
        public int ReviewID { get; set; }
        public Movie MovieReviewed { get; set; }
        public User Reviewer { get; set; }
        public int Rating { get; set; }
        public string Review { get; set; }
        public DateTime DateReviewed { get; set; }

        public MovieReview() { }
    }
}

2 个答案:

答案 0 :(得分:5)

而不是

[HttpPost]
public ActionResult Edit(MovieReview review)

[HttpPost]
public ActionResult Edit(MovieReview model)

(并在该方法中将其从评论重命名为模型。它应该有效。

OR

将MovieReview.Review的属性重命名为其他内容(例如,Review1)。您不能为属性使用相同的名称并传递模型对象(不区分大小写)

答案 1 :(得分:0)

你必须尝试这个

@using (Html.BeginForm("Action methodName","controllerName"))