how to display data using viewdata in asp.net mvc - asp.net-mvc-3

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.

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...

Display particular users data from controller to view

I am doing a project in asp.net mvc. I want to show a particular person's details in the view. I have to join 2 tables to display data. For that I did:
Controller:
[HttpGet]
public ViewResult DisplayData()
{
ViewBag.Designation1up = new SelectList(db.Designations, "Designation1up", "DesignationInternal", "DesignationExternal");
return View();
}
[HttpPost]
public ActionResult DisplayData(Employee emp)
{
try
{
object s = Session["EmployeeID"];
var sessval = s.ToString();
var data1 = (from e in db.Employees.Where(c => c.EmployeeID == sessval) join d in db.Designations on e.Designation1up equals d.Designation1up select e).SingleOrDefault();
return View(data1);
}
catch (Exception e)
{
}
ViewBag.Designation1up = new SelectList(db.Designations, "Designation1up", "DesignationInternal",emp.Designation1up);
return View(emp);
}
The view:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ResourceTracking.ViewModel.AdminDetailsModel>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>DisplayData</title>
</head>
<body>
<fieldset>
<legend>AdminDetailsModel</legend>
<div class="display-label">EmployeeID</div>
<div class="display-field"> <%: Html.DisplayFor(model => model.EmployeeID) %> </div>
<!--...(same DIV 4 other fields)-->
</fieldset>
</body>
</html>
My problem is that, when I debug the code, the compiler is not going into the HttpPost method. It's just debugging the HttpGet method and giving output, but unless HttpPost will run, output will not be proper. What should I do for this?
I think you're a little confused about how ASP.NET MVC works. Normally to display data on a view you will call the HttpGet action (DisplayData), create a model, populate it with the relevant data (the employee) and display it.
Something like this (untested)
[HttpGet]
public ViewResult DisplayData()
{
ViewBag.Designation1up = new SelectList(db.Designations, "Designation1up", "DesignationInternal", "DesignationExternal");
SomeModel model = new SomeModel();
object s = Session["EmployeeID"];
if (s != null)
{
var employeeId = s.ToString();
model.EmployeeData = GetEmployeeData(employeeId);
}
return View(model);
}
private Employee GetEmployeeData(string employeeId)
{
return (from e in db.Employees.Where(c => c.EmployeeID == employeeId)
join d in db.Designations
on e.Designation1up equals d.Designation1up
select e).SingleOrDefault();
}

How to pass error messages to Views?

I want to display error messages in my view. What is the best way to do this?
What replaces the "???" in my code below? I don't want to simply use Html.ValdiationSummary because right now I'm thinking I need to process the list myself and place certain error messages in different places. For example, the code below would actually need to be expanded to put some of the error messages in a floating div, while others may be displayed at the top of the page.
Is there a better way to do this altogether? e.g. Should I be using an entirely different approach to passing error messages from my controller to the view?
My Controller:
public ActionResult ForgotUsername(ForgotUsernameModel model)
{
...
if (!Users.CheckUsername(model.UserName)) {
ModelState.AddModelError("", "That username does not exist.");
}
....
return View(model);
}
My View:
....
<%
if (???) {
foreach (KeyValuePair<string, ModelState> item in ViewData.ModelState) {
if (item.Value != null && item.Value.Errors != null && item.Value.Errors.Count > 0) {
foreach (ModelError e in item.Value.Errors) {
Response.Write(String.Format("<div>{0}</div>", e.ErrorMessage));
}
}
}
}
%>
<% if (!ViewData.ModelState.IsValid) { %>
<%= Html.ValidationSummary(true) %>
<% } %>
or simply:
<%= Html.ValidationSummary(true) %>

ASP.Net MVC ViewData Issue

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();

asp.net mvc 2 client side validation missing ValidationRules on custom attribute

Can't seem to get checkbox to be validate on client-side using asp.net mvc 2. Here is my code.
Model
[Serializable]
public class RegistrationModel
{
bool termsAndCondition = false;
[RequiredToBeTrue(ErrorMessage = "Need terms and service")]
public bool TermsAndConditions
{
get
{
return termsAndCondition;
}
set
{
termsAndCondition = value;
}
}
}
Custom Attribute
public class RequiredToBeTrueAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
return (value != null) && (value is bool) ? (bool)value : false;
}
}
View
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<RegistrationModel>" %>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("Register", "Registration", new { area="Account", id = "openid_form", inRegistration = true }))
<%=Html.ValidationSummary(false) %>
blah blah blah
<div class="checkbox"><label><%= Html.CheckBoxFor(model => model.TermsAndConditions) %>I agree to the terms and conditions of use.</label></div>
<input type="submit" id="submit" name="submit" value="Join Now" />
<%
Html.ValidateFor(m => m.TermsAndConditions);
%>
<% } %>
I am trying to call Html.ValidateFor at the end to push up all error message at top of the page. However, the property "TermsAndConditions" is not getting validated on client side (works great on server side). This leads me to look at the the window.mvcClientValidationMetData method at that mvc push out and I saw the following:
{"FieldName":"TermsAndConditions","ReplaceValidationMessageContents":false,"ValidationMessageId":null,"ValidationRules":[]}
Which you can see that "ValidationRules" are empty meaning that it is trying to validate it but the error message wasn't push out to the client for some reason.
Any ideas? Any help is appreciated.
Seems like I need to do more digging first. Was hoping the new attribute will appear magically on the client side. Instead, have to write some customer javascript to wire it up. See phil hack's post for detail.
This article from Phil Haack, ASP.NET MVC 2 Custom Validation, should help point you in the right direction.
Basically you need to create your own DataAnnotationsModelValidator<RequiredToBeTrueAttribute> and then write some client side script to get it done.
HTHs,
Charles

Resources