ASP.Net MVC ViewData Issue - linq

I have the following code:
private Models.mediamanagerEntities dataModel = new Models.mediamanagerEntities();
public ActionResult Index(FormCollection form)
{
ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();
return View();
}
View:
%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<Project_Name.Models.Item>>" %>
<% foreach (var m in ViewData.Model)
{ %>
Title: <%= m.Title %>
<% } %>
I get the following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Data.Objects.DataClasses.EntityCollection1[Project_Name.Models.Item]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Project_Name.Models.Item].
I'm not too sure what it happening here or how to rectify it, Thanks.

Your LINQ is creating a list like this List<EntityCollection<Item>>, when your view wants List<Item>.
I don't know query syntax for LINQ very well, but this is how you'd get what you want with function syntax:
ViewData.Model = dataModel.Customers.SelectMany(c => c.Type.Items).ToList();
That will take the many Items under each customer and flatten them into one list of Items.

Replace this line:
ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();
with the following:
ViewData.Model = dataModel.Type.ToList();

Related

Kendo tooltip empty with LoadContentFrom

When using LoadContentFrom in my Kendo.Tooltip, the tooltip is always empty, all I see is a grey box the size I specified. It does go to the controller to get the data (verified with breakpoint), but after that, nothing.
If I use ContentTemplateId instead, it shows the template, but I really need to get some dynamic data from the server.
What am I missing to fix this?
Thanks
<%:Html.Kendo().Tooltip()
.For("#alertPanel")
.LoadContentFrom("AlertsDetails", "Home")
.Width(320).Height(320)
%>
Controller:
public ActionResult AlertsDetails()
{
List<object> list = new List<object>();
//fill list with data ...
ViewBag.title = "New alerts";
return PartialView(list);
}
Answer: You can't return data the way I was doing. You need to format the data server-side in an HTML string and set the result in the ViewBag.
public ActionResult AlertsDetails()
{
ViewBag.Title = "<a href='#'>A link</a>";
return PartialView();
}
and
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%= ViewBag.Title%>
That's it...

how to display data using viewdata in asp.net mvc

Given below was my code, and when i am login in form at time error will occur is that " Object reference not set to an instance of an object. ".Actually i m display data in master page.
Master page:-
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<%# Import Namespace="ClientProj.Models" %>
<%foreach(var m in (IEnumerable<user_master>)ViewData["email"])
{ %>
<%=m.email %>
<%} %>
And My Controller :-
public ActionResult Index()
{
ViewData["email"] = from p in db.user_master select p;
return View();
}
[HttpPost]
public ActionResult Index(user_master log)
{
ViewData["email"] = from p in db.user_master where
p.user_id==Convert.ToInt32(Session["user"]) select p;
var ss = from p in db.user_master
where p.username == log.username &&
p.user_password == log.user_password
select p;
if (ss.Count() > 0)
{
Session["id"] = ss.First().user_id;
Session["user"] = ss.First().username;
return RedirectToAction("Home");
}
else
{
return RedirectToAction("index");
}
return View();
}
You're setting ViewData in your controller in one method, but trying to read it out in the master page for ANY page. This means you'll need to ensure that every action you have sets the Viewdata, which is really a bad idea.
What's probably happening here is that you've got another action which isn't setting the ViewData, such as the HttpPost version of Index.

Best way to pass single value from view to controller

I have a form that posts a single value, but I cant seem to get it to the controller. I have verified the value exists in the form, but it arrives at the controller as null. Here is the form post:
<%Html.BeginForm("SaveRecord", "NewApplicant", FormMethod.Post, new { id = Model.PersonModel.ApplicantID } ); %>
<%: Html.Hidden("NewId", Model.PersonModel.ApplicantID) %>
<input type="submit" class="SKButton" value="Save" title="Save this new application as a unique record." />
<% Html.EndForm(); %>
and here is the contoller action:
public ActionResult SaveRecord(NewApplicantViewModel model)
{
int NewAppId = model.PersonModel.ApplicantID;
I have also tried:
public ActionResult SaveRecord(int NewId)
{
model.PersonModel.ApplicantID = NewId;
These must be a simple fix, and I want to pass the id in the model, dont want to use ajax. Thoughts?
Try using:
<%: Html.HiddenFor(model => model.PersonModel.ApplicantID) %>

What's wrong with Razor markup?

I am trying to learn MVC and using samples from the "Pro ASP .net MVC 2". Only I'm trying to write everything in MVC3.
first I had some problem with #Html.RenderAction thing, I changed it to #Html.Action - it did the trick.
Now I have a problem. Could you tell me why ascx view works and similar Razor doesn't?
ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SportsStore.WebUI.Models.NavLink>>" %>
<% foreach (var link in Model) { %>
<%: Html.RouteLink(link.Text, link.RouteValues, new Dictionary<string, object> {
{ "class", link.IsSelected ? "selected" : null }
}) %>
<% } %>
Razor:
#model IEnumerable<SportsStore.WebUI.Models.NavLink>
#foreach (var link in Model)
{
Html.RouteLink(link.Text, link.RouteValues, new Dictionary<string, object> { { "class", link.IsSelected ? "selected" : null } });
}
The Html.RouteLink method returns an IHtmlString.
It does not write anything to the page.
You need to write the returned IHtmlString to the page by writing #Html.RouteLink(...).
This is Razor's equivalent to the <%: Html.RouteLink(...) %> in the ASCX page.
Try this:
#model IEnumerable<SportsStore.WebUI.Models.NavLink>
#foreach (var link in Model)
{
#Html.RouteLink(link.Text, link.RouteValues, new { #class = link.IsSelected ? "selected" : string.empty });
}

How can I get access to a variable in a View which was created in a Controller?

How can I get access to a variable in a View which was created in a Controller?
Either put the variable into the Model that you are using for your View
Or use a ViewBag variable - e.g. from http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
and
<p>
My name is
<b><%: ViewBag.Name %></b>,
<b><%: ViewBag.Age %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
although hopefully you'll be using Razor :)
You need to send the variable to the view in the ViewModel (the parameter to the View() method) or the TempData dictionary.
You can add it to the ViewData[] dictionary or the (newer) ViewBag dynamic.
In your controller:
ViewData['YourVariable'] = yourVariable;
// or
ViewBag.YourVariable = yourVariable;
In your view:
<%: ViewData["yourVariable"] %>
// or
<%: ViewBag.YourVariable %>

Resources