3

我需要知道是否有办法将视图(Razor 引擎)的模型(或其一部分,即其后的搜索查询)数据传递给控制器​​。

为了更好地解释我必须做什么,这是感兴趣的代码:

看法:

@model IEnumerable<MvcMovie.Models.Movie>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

...
@foreach (var item in Model) { ...}
...

@Html.ActionLink("Search", "SearchIndex")
@Html.ActionLink("Create Document", "createDoc"/*, new { id = Model.ToList() }*/)

我想通过

@model IEnumerable<MvcMovie.Models.Movie>

在第一行(= foreach 指令中使用的模型)向控制器“createDoc”创建与视图动态绑定的报表文档。

我尝试了一切:我尝试使用 ViewData (VIEW: ViewData["data"]=Model , CONTROLLER List movies= ViewData["data"]),我同样尝试了 TempData,我尝试将模型作为 routeValues 传递给ActionLink(如您所见:new{ id= Model.toList() }),但没有任何效果。

甚至有可能做我想做的事吗?

谁能帮我?

4

2 回答 2

2

你的模型不应该是IEnumerable<MvcMovie.Models.Movie> 它应该是一个类,比如说SearchMovieModelIEnumerable<MvcMovie.Models.Movie> Movies它的属性之一。

如果你想要一个搜索模型,这样的东西是合适的:

public class SearchMovieModel{
    public IEnumerable<MvcMovie.Models.Movie> Movies {get;set;}
    public string SearchString {get;set;}
}

您在视图和控制器中引用此模型及其属性。

我想我应该在控制器中添加解析这个的方法。

在第一次调用视图时,模型不存在。您需要在控制器中创建它:

public ActionResult Search(){
    var model = new SearchMovieModel();
    //you also need to instantiate the null objects unless you do that in the model's constructor
    model.Movies = new List<Movie>();
    return View(model);
}

要将 POST 数据“重新转换”回模型,您需要指定模型和方法:

[HttpPost]
public ActionResult Search(SearchMovieModel model){
    if (ModelState.IsValid){
        //populate your IEnumerable<Movie> here.
        return View(model);
    }
    // the complex collection will not be parsed back into the model.  You will need to repopulate it.
    model.Movies = new List<Movie>();
    return View(model);
}
于 2012-06-01T15:54:34.680 回答
1

我认为那知道你想要什么......但是这段代码

@Html.ActionLink("Create Document", "createDoc", new { id = Model.ToList() })

你的html是..

<a href="/test/createDoc?id=System.Collections.Generic.List%601%5BMvcMovie.Models.Movie%5D">Create Document</a>

那是因为是呈现类型而不是数据

解决方案

  1. 定义过滤器模型以再次进行搜索(jeremy-holovacs和我的推荐)为什么再次向服务器询问相同的数据?因为如果有人分享那个链接......你可以想象结果是什么,甚至注入你的应用程序将生成的假数据

  2. 将数据序列化为 json,例如将其转发到控制器

于 2012-06-01T19:19:52.010 回答