Unable to access the object which is defined in the model class - asp.net-mvc

I am trying to list a data which is presented in the database and i created a class ViewingGoals and implement its business logic in the class ViewingGoalsBusinessLayer codes are as like follows
ViewingGoals.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer
{
public class ViewingGoals
{
public string Goal { get; set; }
}
}
ViewingGoalsBusinessLayer.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using BusinessLayer;
namespace BusinessLayer
{
public class ViewingGoalsBusinessLayer
{
public void ViewData(ViewingGoals viewgoal)
{
try
{
string Connectionstring = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
List<ViewingGoals> viewgoals = new List<ViewingGoals>();
using (SqlConnection con = new SqlConnection(Connectionstring))
{
SqlCommand cmd = new SqlCommand("ViewGoal", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//ViewingGoals viewgoal = new ViewingGoals();
viewgoal.Goal = rdr["Goal"].ToString();
viewgoals.Add(viewgoal);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
and my controller code is :
ViewingGoalsController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer;
namespace AppraisalManagementSystemFinal.Controllers
{
public class ViewingGoalsController : Controller
{
//
// GET: /ViewingGoals/
public ActionResult ViewingGoals()
{
ViewingGoalsBusinessLayer viewinggoalsbusinessLayer = new ViewingGoalsBusinessLayer();
List<ViewingGoals> viewgoals = viewinggoalsbusinessLayer.viewgoal.ToList();
return View(viewgoals);
}
}
}
in that controller wen i am trying to access the object from the ViewingGoalBusinessLayer
List viewgoals = viewinggoalsbusinessLayer.viewgoal.ToList(); i got error as doesnot contain a definition for viewgoal.
please help me to overcome it.

When you use viewinggoalsbusinessLayer.viewgoal, you are trying to access a viewgoal property from your viewinggoalsbusinessLayer object.
Problem is that you haven't defined such a property in that object !
Here is an updated part of your code
public class ViewingGoalsBusinessLayer
{
public List<ViewingGoals> ViewGoals;
public void ViewData(ViewingGoals viewgoal)
{
try
{
string Connectionstring = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
Viewgoals = new List<ViewingGoals>();
// Rest of code is unchanged ...
}
catch (Exception ex)
{
throw ex;
}
}
}
Next problem is that you'll need to initialize that list, and I'm not sure what your ViewData function is doing...

Related

ASP.NET My Music Store

I need help Sir, newbie in MVC, I would like to ask why I can't find
the store DB even it is declared at the bottom.
The "storeDB" does not exist in the current context
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMusicStore.Models;
namespace MyMusicStore.Controllers
{
public class StoreController : Controller
{
//
// GET: /Store/
public ActionResult Index()
{
var genres = storeDB.Genres.ToList();
return View(genres);
}
public ActionResult Browse(string genre)
{
var newGenre = new Genre { Name = genre };
return View (newGenre);
}
public ActionResult Details(int id)
{
var album = new Album { Title = "Album" + id };
return View(album);
}
public class StoreController : Controller
{
MusicStoreEntities storeDB = new MusicStoreEntities();
}
}
}
Inside of the class StoreController, you declare StoreController a second time, and declare the variable inside that. What you've made is what's called an 'inner class', and the inner class is DIFFERENT from the outer class even though it appears to have the same name, it is brand new.
So you meant to do this instead:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMusicStore.Models;
namespace MyMusicStore.Controllers
{
public class StoreController : Controller
{
//
// GET: /Store/
public ActionResult Index()
{
var genres = storeDB.Genres.ToList();
return View(genres);
}
public ActionResult Browse(string genre)
{
var newGenre = new Genre { Name = genre };
return View (newGenre);
}
public ActionResult Details(int id)
{
var album = new Album { Title = "Album" + id };
return View(album);
}
MusicStoreEntities storeDB = new MusicStoreEntities();
}
}

MVC c# controller return view()

below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models = We.Models;
using We.BAL;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Helpers;
using System.Diagnostics.CodeAnalysis;
using System.Security.Principal;
using System.Web.Routing;
using System.Web.Security;
using PagedList;
using We.Models.ViewModels;
using We.Models.Interface;
using We.Models.DBData;
using We.Models.Repository;
using System.Data.Sql;
using System.Data.Query;
using System.Data.SqlClient;
namespace We.Controllers
{
public class ClientEnquiryController : Controller
{
private Models.Interface.IPolicyService _repository;
private Models.Repository.PolicyServiceRepository clientenqRepository;
public ClientEnquiryController()
: this(new Models.Repository.PolicyServiceRepository())
{
}
public ClientEnquiryController(Models.Interface.IPolicyService repository)
{
_repository = repository;
}
public ActionResult MasterView( string PolicyNo, string carrierCode, string sPol, string languageCode)
{
carrierCode = "2";
sPol = "502-0877220";
languageCode = "eng";
return View(_repository.policymaster(carrierCode, sPol, languageCode));
}
From my codeI am do the return like this :
return View(_repository.policymaster(carrierCode, sPol, languageCode));
how about if i want return the view with more than one statement in same time? for example:
_repository.policymaster(carrierCode, sPol, languageCode);
_repository.policyAgent(carrierCode, sPol, languageCode);
Anyone can help me?
I think you might benefit from modelling the view with the two return objects. For example,
public class MasterViewVM
{
public PolicyMaster {get; set;}
public PolicyAgent {get; set;}
}
Then you return the view model with the data entities:
public ActionResult MasterView(string PolicyNo,
string carrierCode, string sPol, string languageCode)
{
carrierCode = "2";
sPol = "502-0877220";
languageCode = "eng";
MasterViewVM model = new MasterViewVM
{
PolicyMaster =_repository.policymaster(carrierCode, sPol, languageCode),
PolicyAgent = _repository.policyAgent(carrierCode, sPol, languageCode)
};
return View(model);
}
Another possibility is to use a child action. See
http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

Session across controller becomes null in MVC

My session becomes null when I redirect to another controller's Action, what should I do?
With regards to the comment you posted me, here is what I was thinking. In the Controller where you need the session use something similar to this:
//Controller A
public class TheController : Controller
{
public ActionResult Index(){
Session["yourSession"] = "Hello World";
return View();
}
}
//Controller B
public class MyController : Controller
{
string textString;
protected override void OnActionExecuting(ActionExecutingContext ctx)
{
base.OnActionExecuting(ctx);
textString = ctx.HttpContext.Session["yourSession"].ToString();
}
public ActionResult Index(){
string currentText = textString;
return View();
}
}
I tested the suggestion from (http://stackoverflow.com/questions/889516/session-null-in-asp-net-mvc-controller-constructors), and the contents of the session were available.
You have to create a unique base controller with a session property, then all controllers within your project will inherit from that BaseController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MonitoringCSP.Controllers
{
//[AllowAnonymous]
//[Authorize(Roles = "admin")]
public class BaseController : Controller
{
private HttpSessionStateBase _session;
protected HttpSessionStateBase CrossControllerSession
{
get
{
if (_session == null) _session = Session;
return _session;
}
set {
_session = Session;
}
}
}
}
Usage sample
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MonitoringCSP.Models;
namespace MonitoringCSP.Controllers
{
[AllowAnonymous]
public class AccountController : BaseController
{
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
/*session*/
CrossControllerSession["UserName"] = User.Identity.Name;
/*end session*/
return RedirectToAction("someAction");
}
}
}
I realized that I was clearing and destroying all sessions prior to setting the new session on login like this
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Session.Abandon();
Session.Clear();
When I removed these lines, everything started working like #Clayton said, so I removed these lines and replaced it with Session.Remove('sessionvariablename'), I am still not sure what issue were the above lines causing, but my code started working.
Make sure your controller does not have this attribute set on it:
[SessionState(SessionStateBehavior.Disabled)]

Why is of two same types of xmls, one is not deserializing and the other is?

Suppose I have two different xml files as embedded-resource in a same assembly:
Hummer.xml
<?xml version="1.0" encoding="utf-8" ?>
<car company="GMC" brand="Hummer" />
HammerHead.xml
<?xml version="1.0" encoding="utf-8" ?>
<shark species="HammerHead" length="45" />
Car.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace XmlDeserialization_Test
{
[XmlRoot("car"), XmlType("car")]
public class Car
{
[XmlAttribute("company")]
public string Company { get; set; }
[XmlAttribute("brand")]
public string Brand { get; set; }
}
}
Shark.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace XmlDeserialization_Test
{
[XmlRoot("shark"), XmlType("shark")]
public class Shark
{
[XmlAttribute("species")]
public string Species { get; set; }
[XmlAttribute("length")]
public double Length { get; set; }
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;
namespace XmlDeserialization_Test
{
class Program
{
static void Main(string[] args)
{
List<Car> carList = new List<Car>();
List<Shark> sharkList = new List<Shark>();
Assembly assembly = Assembly.LoadFrom("XmlDeserialization_Test.exe");
string[] manifestResourceNames = assembly.GetManifestResourceNames();
Array.Sort<string>(manifestResourceNames);
foreach (string mrn in manifestResourceNames)
{
Stream stream = assembly.GetManifestResourceStream(mrn);
XmlSerializer serializer = new XmlSerializer(typeof(Shark));
object obj = serializer.Deserialize(stream);
if (obj is Car)
{
carList.Add((Car)obj);
}
else if (obj is Shark)
{
sharkList.Add((Shark)obj);
}
}
}
}
}
HammerHead - Shark is deserializing perfectly.
But, Hummer - car is not. The following exception is being generated:
There is an error in XML document (2, 2).
"<car xmlns=''> was not expected."
If Shark is deserializing, why Car is not? If Car is generating exception, why Shark is not?
I am clueless!!!
You're trying the desearilize a 'car' object with a 'shark' deserialize it. If you change to create a deserializer of type Car, you'll have the opposite result:
XmlSerializer serializer = new XmlSerializer(typeof(Car));
I don't know how you're serializing, but this should give you an idea.

How to create a strongly typed MVC View based on a custom Linq2Sql class

I have created a custom entity because I need to populate an entity with some data from a join in L2S.
When I right click on the ActionResult code in the Controller to "Add View", and then choose "Create strongly typed view", my class doesn't show up in the classes available in the selector. I'm not sure why. Here is my code:
//The Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace FurnitureStore.Models.Repository
{
public class FurnitureRepository
{
public IQueryable<Listing> GetProductListings()
{
FurnitureDataContext dc = new FurnitureDataContext();
return (from p in dc.Products
join c in dc.Categories
on p.CategoryId equals c.CategoryId
select new Listing
{
ProductName = p.ProductName,
CategoryDescription = c.CategoryDescription
});
}
}
}
//The entity class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FurnitureStore.Models
{
public class Listing
{
public string ProductName { get; set; }
public string CategoryDescription { get; set; }
}
}
//The Method in the Controller
public ActionResult ProductListings()
{
FurnitureRepository fr = new FurnitureRepository();
var listings = fr.GetProductListings();
return View("ProductListings",listings);
}
Make sure that you compile the code, if the code is not compiled the newly added classes dont showup in the classes available in the selector
Just create a normal view and edit the view's page definition (inherits attribute specifically) yourself.
<%# Page ... Inherits="System.Web.Mvc.ViewPage<IQueryable<FurnitureStore.Models.Listing>>" %>
Off the top of my head I can't answer why it isn't appearing in your class selector.
HTHs
Charles

Resources