MVC c# controller return view() - asp.net-mvc

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

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

Why does RedirectToActionResult ControllerName return NULL?

I have a Xunit test class for a MVC:
using System;
using Xunit;
using Home.Controllers;
using Microsoft.AspNetCore.Mvc;
using Tester.Models;
using Xunit.Abstractions;
namespace ClassLibrary1
{
public class Class1
{
[Fact]
public void CreateinController()
{
HomeController c = new HomeController();
var result = c.Create();
//result moet een view zijn
var viewResult = Assert.IsType<ViewResult>(result);
//Juiste redirection
var result2 = c.Create(null);
var redirectToActionResult =
Assert.IsType<RedirectToActionResult>(result2);
Assert.Equal("Home", redirectToActionResult.ControllerName);
Assert.Equal("BoekingVerwerken", redirectToActionResult.ActionName);
}
}
}
Whenever I run the test the ActionName passes the test because it actually contains the value. But the ControllerName seems to be NULL valued, why is this?
When the Action has a value why wouldn't the Controller have one? Should I put the controller in the RTA?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Tester.Models;
namespace Home.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(HotelBoeking boeking)
{
return RedirectToAction("BoekingVerwerken", boeking);
}
[HttpGet]
public IActionResult BoekingVerwerken(HotelBoeking boeking)
{
return View(boeking);
}
}
}
If you take a look at the Controller.cs source code, you will see that RedirectToAction returns a RedirectToRouteResult type, not a RedirectToActionResult type.
As you can see from the source code of RedirectToRouteResult.cs, you can get the controller name from the RouteValues property. There is no ControllerName property on this type.
var redirectToRouteResult =
Assert.IsType<RedirectToRouteResult>(result2);
Assert.Equal("Home", redirectToRouteResult.RouteValues["controller"]);
I am not entirely sure the syntax for XUnit is correct, as I don't work with it much, but you should take away from this that because MVC is open source that questions like this one can be easily answered by inspecting the source code.

Unable to access the object which is defined in the model class

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

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

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

Resources