如何在ASP.MVC中将对象从一个视图传递到另一个视图

时间:2013-07-29 14:35:36

标签: asp.net-mvc razor

我仍然不太清楚如何在一个cshtml文件中使用信息,从另一个cshtml文件获取。我的节目由一个画廊组成。当用户点击其中一个图片时,我想重定向到另一个显示与该图片有关的图片和信息的视图,而不是简单地指向仅包含图片网址的页面。以下是我错误尝试的相关代码:

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var client = new WebClient();
        var response = client.DownloadString(Url.Action("gallery", "photo", null, Request.Url.Scheme));
        var jss = new JavaScriptSerializer();
        var result = jss.Deserialize<List<Photo>>(response);

        return View();
    }
    public ActionResult FullImage(Photo m)
    {
        return View();
    }
}   

查看:

@section mainContent {
  <ul class="thumbnails">
    @foreach (var photo in Model)
    {
      <li class="item">
         <a href='@Url.Action("FullImage", "Home", new {imageUrl="~/photos/" + photo.FileName, title= photo.Title, description= photo.Description})'>
             <img alt="@photo.Description" src="@Url.Content("~/photos/" + photo.FileName)" class="thumbnail-border" width="180" />
         </a>
         <span class="image-overlay">@photo.Title</span>
      </li>
    }
  </ul>
}

型号:

namespace PhotoGallery.Models
{
    public class Photo
    {
        public string Title { get; set; }
        public string FileName { get; set; }
        public string Description { get; set; }
        public string imageUrl { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

您无法使用操作链接绑定到模型。您需要将主键或唯一键传递给Action,并根据键在Action中找到您的Model。

例如,您可以在视图中执行此操作:

@section mainContent {
  <ul class="thumbnails">
    @foreach (var photo in Model)
    {
      <li class="item">
         <a href='@Url.Action("FullImage", "Home", new { fileName = photo.FileName})'>
             <img alt="@photo.Description" src="@Url.Content("~/photos/" + photo.FileName)" class="thumbnail-border" width="180" />
         </a>
         <span class="image-overlay">@photo.Title</span>
      </li>
    }
  </ul>
}

然后,在你的行动中,你将拥有:

public ActionResult FullImage(string fileName)
{
    // Example of some code to get the photo from the repository. It's better to use a photoID instead of the fileName.
    var photo = db.Photos.FindPhoto(fileName);
    return View();
}