1

我仍然不太了解如何使用从另一个 cshtml 文件获取的一个 cshtml 文件中的信息。我的程序由一个画廊组成。当用户单击其中一张图片时,我想重定向到显示图片和与该图片有关的信息的另一个视图,而不是简单地指向仅包含图像 url 的页面。这是我错误尝试的相关代码:

控制器:

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; }
    }
}
4

1 回答 1

1

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

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

@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>
}

然后,在您的 Action 中,您将拥有:

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();
}
于 2013-07-29T15:21:47.533 回答