如何在视图的方法签名中为变量赋值?

时间:2018-03-29 05:55:23

标签: c# asp.net-mvc

以下是控制器类中的view方法:

        public ViewResult Show(int id)
        {
            ShowViewModel showView = new ShowViewModel();
            showView.Show = _Repository.GetById(id);

            ViewBag.title = showView.Show.collectionName;
            return View(showView);
        }

这是GetByID()方法:

        public PodcastShow GetPodcastById(int Id)
        {
            foreach(var show in podcasts)
            {
                if(show.NameRoute == podId)
                {
                    return show;
                }
            }
            return podcasts.FirstOrDefault();
        }

我需要为" int ID"分配一个值。变量,所以我可以使用特定的对象数据来创建Show视图。

提前致谢!

这是主页视图:

@model PodcastListViewmodel;

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.title</title>
</head>
<body>
    @foreach (var podcast in Model.Podcasts)
    {

                <div class="thumbnail">
                    <a href="./podcast/show/@podcast.NameRoute">
                        <img src="@podcast.ImageUrl" width="200" height="200" />
                    </a>
                </div>

    }
</body>
</html>

这是show view,我试图用用户选择的数据创建:

@model ShowViewModel

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.title</title>
</head>
<body>
    <img src="@Model.Show.artworkUrl600" width="200" height="200"/>
    <h2>@Model.Show.collectionName</h2>
</body>
</html>

PodcastShow类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PodCast.Models
{
    public class PodcastShow
    {
        public int collectionId { get; set; }
        public string collectionName { get; set; }
        public string artworkUrl600 { get; set; }
        public string ImageUrl { get; set; }
        public string releaseDate { get; set; }
        public string feedUrl { get; set; }
        public string NameRoute { get; set; }
        public List<PodcastEpisode> Episodes { get; set; }


    }
}

2 个答案:

答案 0 :(得分:1)

试试这个:

public ViewResult Show(string id)
{
     ShowViewModel showView = new ShowViewModel();
     showView.Show = _Repository.GetPodcastById(id);

     ViewBag.title = showView.Show.collectionName;
     return View(showView);
}

public PodcastShow GetPodcastById(string Id) 
{ 
    return podcasts.Single(x => x.NameRoute == Id); 
}

答案 1 :(得分:0)

目前还不太清楚你的实体是什么样的,但我认为你需要这样的东西:

public PodcastShow GetPodcastById(int Id)
{
    return podcasts.FirstOrDefault(x=>x.NameRoute==Id);
}

鉴于NameRoute是您正在寻找的ID。