Reputation: 4662
I am passing to my Razor view this:
public ActionResult NewsList()
{
ViewBag.News = _client.GetNews(Guid.Parse(GetCookieInfo.TokenId));
return View();
}
And my GetNews is this:
public IEnumerable<TokenNews> GetNews(Guid tokenid)
{
var nl = from news in entities.News
where news.TokenId == tokenid &&
DateTime.Now > news.Expiration &&
news.IsActive
orderby news.OrderNumber
select new News
{
NewsTitle = news.NewsTitle,
NewsBody = news.NewsBody,
OrderNumber = news.OrderNumber
};
var newslist = new List<TokenNews>();
foreach (var news in nl)
{
var nw = new TokenNews();
nw.Body = news.NewsBody;
nw.Title = news.NewsTitle;
newslist.Add(nw);
}
return newslist;
}
And my TokenNews is this:
[DataContract]
public class TokenNews
{
private string title = string.Empty;
private string body = string.Empty;
public string Title {
get { return title; }
set { title = value; }
}
public string Body
{
get { return body; }
set { body = value; }
}
}
My NewsList.cshtml view looks like this:
@using SuburbanCustPortal.SuburbanService
<br />
@foreach (var nws in (IEnumerable<TokenNews>) ViewBag.News)
{
<div class="leftdiv">
<br/>
<label class="sizedCustomerlabel">
@nws.Body
</label>
</div>
}
My problem is the @nws.Body
. The nws is not giving me the Title or Body in my TokenNews.
It is giving me the message:
Cannot resolve symbol body.
This has to be something I'm overlooking a hundred times but I just cannot figure it out.
Any suggestions?
UPDATE
In response to Umar Farooq Khawaja:
I did as you showed and this is what happened:
Upvotes: 0
Views: 133
Reputation: 3987
You need to apply DataMember
attribute to your TokenNews
class on the public properties. Remember to regenerate the client for the SuburbanCustPortal.SuburbanService
service that uses the TokenNews
class afterwards. I also used auto-generated properties rather than ones backed by private fields just to make the code a bit cleaner.
[DataContract]
public class TokenNews
{
[DataMember]
public string Title
{
get;
set;
}
[DataMember]
public string Body
{
get;
set;
}
}
If this doesn't work, try first storing ViewBag.News
in a statically typed variable and then iterating over it using the new statically typed reference, e.g.
<br />
@{
var news = (IEnumerable<TokenNews>)ViewBag.News;
}
@foreach (var item in news)
{
<div class="leftdiv">
<br />
<label class="sizedCustomerLabel">
@item.Body
</label>
</div>
}
Also, you can refactor the following method this way:
public IEnumerable<TokenNews> GetNews(Guid tokenid)
{
var newslist = from news in entities.News
where news.TokenId == tokenid &&
DateTime.Now > news.Expiration &&
news.IsActive
orderby news.OrderNumber
select new TokenNews
{
Title = news.NewsTitle,
Body = news.NewsBody
};
return newslist.ToArray();
}
Upvotes: 1