ASP.NET My Music Store - asp.net-mvc

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

Related

Is there get method which not found while run web api service

I'm creating a web api controller and implement ([HttpGet])parameterized get method with datatype class but when I run this its show 404 Not Found.
When i am implementing normal datatype like string or int its show me the answer or datatype like List still it's giving me answer but when I directly declare datatype as class like Student its show 404 not found error. I don't know why it's so. I am trying to learn web api with mvc please help me.
I am creating one simple class Student and one studentapicontroller.In my api controller, I create get method with datatype class and for testing purpose i make other get method with different datatype
Student.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace epay.Models
{
public class student
{
public int id { get; set; }
public string name { get; set; }
}
}
studentapiController :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using epay.Models;
namespace epay.Controllers
{
public class studentapiController : ApiController
{
// GET api/studentapi
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/studentapi/5
{
return "value";
}
// POST api/studentapi
public void Post([FromBody]string value)
{
}
// PUT api/studentapi/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/studentapi/5
public void Delete(int id)
{
}
//POST api/studentapi/
[HttpGet]
public student getdetails(int id, string na)
{
student st = new student();
st.id = id;
st.name = na;
return st;
}
//GET api/studentapi/getstud
[HttpGet]
public List<student> getstud()
{
List<student> lst = new List<student>();
student st = new student();
st.name = "manlai";
st.id = 5;
lst.Add(st);
return lst;
}
}
}
I just want getdetails result or how to do if I want my method datatype as a class and I am passing parameter with my get method how to do this
Make getdetails route like below because it is conflicting with get
[HttpGet("getdetails")]
public student getdetails(int id, string na)
{
student st = new student();
st.id = id;
st.name = na;
return st;
}
you can call route something like this with querystring /studentapi/getdetails?id=1&na=test

OData V4 attribute routing not using the right action

i am experiencing a problem with attribute routing in OData V4. I have a simple Customers model class and a Controller, which has 2 Get methods. However, whenever i try to GET a specific Customer like /Customers(7) , it always uses the second Get method to get all customers, but never breaks into the method with the id parameter. What am i missing here? Thank you!
The controller:
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Routing;
using API.Models;
namespace API.Controllers
{
public class CustomersController : ODataController
{
private OContext db = new OContext();
// GET: Customers(5)
[HttpGet]
[ODataRoute("Customers({id:int})")]
[EnableQuery]
public SingleResult<Customers> Get([FromODataUri] int id)
{
IQueryable<Customers> result = db.Customers.Where(p => p.Id == id).AsQueryable();
return SingleResult.Create(result);
}
// GET: Customers
[HttpGet]
[ODataRoute("Customers")]
[EnableQuery]
public IQueryable<Customers> Get()
{
return db.Customers.AsQueryable();
}
}
}
The WebApiConfig:
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using API.Models;
using Microsoft.OData.Edm;
namespace API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.MapHttpAttributeRoutes();
config.MapODataServiceRoute("odata", null, GetEdmModel());
config.EnsureInitialized();
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "API.Controllers";
builder.ContainerName = "DefaultContainer";
builder.EntitySet<Customers>("Customers").EntityType.HasKey(c => c.Id);
builder.EntitySet<Customers_CustomField> ("Customers_CustomFields");
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
}

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)]

Base Controller Get Value

I having trouble getting a value to my base controller. All I would like to do is have my base controller pick up an ID from an ActionLink?
Link
<%= Html.ActionLink("About Us", "About", new { SectionId = 1 })%>
Base Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Website.Controllers
{
public class SectionController : Controller
{
//
// GET: /Section/
public SectionController(int SectionId)
{
if (SectionId == 1)
{
ViewData["Message"] = "GOT AN ID";
}
else
{
ViewData["Message"] = "NO ID";
}
}
}
}
Home Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Website.Controllers
{
[HandleError]
public class HomeController : SectionController
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Contact()
{
return View();
}
}
}
Solution so far
ActionLink
<%= Html.ActionLink("About Us", "About", new { SectionId = 1})%>
SectionAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Website.ActionFilters
{
public class SectionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Actions have sectionId parameter
object SectionId = filterContext.ActionParameters.FirstOrDefault(x => x.Key == "SectionId").Value;
if (SectionId != null && (int)SectionId == 1)
{
filterContext.Controller.ViewData["Message"] = "GOT AN ID";
}
else
{
filterContext.Controller.ViewData["Message"] = "NO ID";
}
}
}
}
SectionController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Website.ActionFilters;
namespace Website.Controllers
{
[Section]
public class SectionController : Controller
{
}
}
View
<%= Html.Encode(ViewData["Message"]) %>
Your code won't work. Instead you should define OnActionExecuting method in base controller, where you get actual sectionId from route data and set ViewData accordingly. Try something like this (not tested):
public class SectionController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Actions have no sectionId parameter - look for it in querystring
string SectionId = filterContext.HttpContext.Request.QueryString["sectionId"];
int sId;
if (int.TryParse(SectionId, out sId) && sID == 1)
{
filterContext.Controller.ViewData["Message"] = "GOT AN ID";
}
else
{
filterContext.Controller.ViewData["Message"] = "NO ID";
}
}
}
Updated:
You can move this out from controller and create ActionFilter. It is very simple:
public class SectionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Actions have sectionId parameter
object SectionId = filterContext.ActionParameters
.FirstOrDefault(x => x.Key == "sectionId").Value;
if (SectionId != null && (int)SectionID == 1)
{
filterContext.Controller.ViewData["Message"] = "GOT AN ID";
}
else
{
filterContext.Controller.ViewData["Message"] = "NO ID";
}
}
}
...
[Section]
public class SectionController : Controller {
or
[HandleError, Section]
public class HomeController : SectionController {
A constructor of a base controller is not typically the place where common code is placed. You usually create a filter for common code. If you decorate the base controller with this filter attribute, then all inheriting controllers use that filter.

Resources