开发者

Accessing Linq Values in ViewData

I'm having trouble accessing the id, area and theme values in my ViewData.

They are being set in my action filter but when I get to the Site.Master I don't have access to them.

Any hel开发者_运维技巧p or advice would be great.

ActionFilter

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    int SectionID = Convert.ToInt32(filterContext.RouteData.Values["Section_ID"]);
    int CourseID = Convert.ToInt32(filterContext.RouteData.Values["Course_ID"]);

        if (CourseID == 0)
        {
            filterContext.Controller.ViewData["Styles"] = (from m in _dataContext.Styles where m.Area_ID == SectionID select new {theme = m.Area_FolderName }).ToList();
        }
        else
        {
            filterContext.Controller.ViewData["Styles"] = (from m in _dataContext.Styles where m.Course_ID == CourseID select new { theme = m.Course_FolderName }).ToList();
        }
    }
}

Site.Master

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<%@ Import Namespace="Website.Models" %>

    <%       
        foreach (var c in (IEnumerable<Styles>)ViewData["Styles"])
       {
        Response.Write(c.Theme);
    }%>


Editting again based on your feedback...

I think you'd best be served by creating a ViewModel so that you can strongly type your View.

Create a class like the following (you can add fields as needed):

public class StyleViewModel
{
    public string Id {get; set;}
    public string Area {get; set;}
    public string Theme {get; set;}
}

Then in your controller:

filterContext.Controller.ViewData["Styles"] = 
    (from m in _dataContext.Styles 
    where m.Area_ID == SectionID
    select new StyleViewModel
    {
        Id = m.Area_ID
        Area = m.Area_Name
        Theme = m.Area_FolderName
    }).ToList();

You can then clean up the code in your View:

<% 
    foreach (var c in Model)
    {
        Response.Write(c.Theme);
    }
%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜