Session sets the value successfully but gets null in MVC 5 - c#

I am developing an MVC 5 application and I have a specific Controller for Session variables in my application which has 6 sessions, and all are working fine. Now I wanted to use another session, so I have declared it in my Session controller as follows:
public int tempResult
{
get { return Convert.ToInt32(Session["tempResult"]); }
set { Session["tempResult"] = value; }
}
Now I have a Controller A which inherits from Session Controller and it is setting the session variable tempResult in method as:
[HttPPost]
public JsonResult COAcodelength(MST m)
{
var s = (from sets in db.ABCs where sets.name == "Name" && sets.pre.ToString() == m.house select sets.Id).Single().ToString();
tempResult = Convert.ToInt32(s);
}
Now Controller B which also inherits from Session Controller is calling a method of Controller A and in that method I am trying to access the session value of tempResult as:
[HttpPost]
public ActionResult New([Bind(Include = "Id,Name,House,Number")] MST tr)
{
tr.Name = r.Ccode(tr); // r is the instance of Controller A
db.MSTs.Add(tr);
db.SaveChanges();
return Json(tr);
}
And the Ccode method in Controller A is as:
public string Ccode (MST tr)
{
int q = tempResult;
tr.Name = q.ToString() + tr.House;
return tr.Name;
}
So, when Ccode method in Controller A tries to get the value of tempResult it returns null with Object reference error.
What could be the possible problem?

You cannot convert null to int 32, which meant that if your tempResult can be null, you should use it like this:
public int? tempResult
{
get { return Convert.ToInt32(Session["tempResult"]); }
set { Session["tempResult"] = value; }
}
Which will then allow the integer variable to accept null.
int? meaning the integer variable can be nullable.

Related

List<int> from method parameters return 0 as default first value in C# MVC ActionResult

I have checked the parameters in chrome network inspection tool. and it's null.
but when I get the data from the actionResult it has a member and it's zero.
[HttpPost]
public ActionResult Index(MyInputDto input)
{
var data = input.ItemList;
//the data variable is a list with one member and that's zero;
return view();
}
and this is my MyInputDto:
public class MyInputDto
{
public MyInputDto()
{
this.ItemList = new List<int>();
}
public List<int> ItemList { get; set; }
}
and the request is something like this:
var itemList = ($('#input_selector').val() != null ? $('#input_selector').val() : []).map(x => parseInt(x));
$.post('#Url.Action("Index")'
, {
ItemList: itemList
})
.done((data) => {
$('[data-table-container]').html(data);
})
the reason I use parseInt(x) is that if I don't the data will be sent like this "1,2,3,4" and the ActionResult method doesn't recognize it as a list of integers
how can I fix it?

Show buttons on a partial view based on some query

I am showing search results same as searching groups on facebook
enter image description here
I have a relationship Table named CommunityUser in Database having attributes CommunityID and UserID.
Using Partial View I want to show if User not already joined that Community/Group that it will show Join Button else if user already joined that community it will show Leave button.
I have written IsMember() function in my controller that takes two parameters, CommunityID and UserID. This will return true if that Community ID exist against that user ID.
public bool IsMember(string UserID, int CommunityID) {
var Membership = db.Users.Include(x => x.CommunityUsers).Where(s => s.Id.Equals(UserID)).Count();
if(Membership>0)
return true;
else
return false;
}
Now what I actually need is, I want to call this function in an IF condition on my view class. It is not allowing me to call this function on my view Class.
#if (){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
In your controller you should have a method which will return this view. So in this method you call this function
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
return View(hasMembership);
}
In the View it self then you just grab this variable hasMembership you just passed from #model.
#if (Model){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
Note: it might be wise to create some DTO class for passing data to a view, because you might need to pass multiple value to a view at some point. Plus the whole condition would be more readable
public SomeDTO {
public bool IsMember {get;set}
public List<Community> Communities {get;set;}
}
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
var listOfCommunities = _repo.GetComunities();
var dto = new SomeDTO
{
IsMember = hasMembership,
Communities = listOfCommunities
}
return View(dto);
}
#if (Model.IsMember){
// do or do not something
}

How to initialize field once for every client in MVC Controller?

In ASP.NET MVC, a field which is declare outside a method, the field is initialize every-time.
There I am giving a demo example.
public class TestController : Controller
{
private List<object> ListItems;
// GET: /Test/Index
public ActionResult Index(int Id)
{
ModelSource _model = new ModelSource(Id);
ListItems = _model.GetItems();//coming info from Model
return View();
}
// GET: /Test/Demo
public ActionResult Demo()
{
int x = ListItems.Count;
//Do Something More
return View(x);
}
}
Is It possible for ListItems will be initialize for once for every client as Id parameter will be different on client's request.
As Patrick Hofman stated you can use Sessions or Cookies Here is an example for both:
Cookies:
string cookievalue ;
if ( Request.Cookies["cookie"] != null )
{
cookievalue = Request.Cookies["cookie"].ToString();
}
else
{
Response.Cookies["cookie"].Value = "cookie value";
}
//For removing cookie use following code
if (Request.Cookies["cookie"] != null)
{
Response.Cookies["cookie"].Expires = DateTime.Now.AddDays(-1);
}
Sessions:
HttpContext.Current.Session.Add("Title", "Data");
string foo = Session["Title"];

C# Enum - How to Compare Value

How can I compare the value of this enum
public enum AccountType
{
Retailer = 1,
Customer = 2,
Manager = 3,
Employee = 4
}
I am trying to compare the value of this enum in an MVC4 controller like so:
if (userProfile.AccountType.ToString() == "Retailer")
{
return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");
I also tried this
if (userProfile.AccountType.Equals(1))
{
return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");
In each case I get an Object reference not set to an instance of an object.
use this
if (userProfile.AccountType == AccountType.Retailer)
{
...
}
If you want to get int from your AccountType enum and compare it (don't know why) do this:
if((int)userProfile.AccountType == 1)
{
...
}
Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.
EDIT (thanks to #Rik and #KonradMorawski) :
Maybe you can do some check before:
if(userProfile!=null)
{
}
or
if(userProfile==null)
{
throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}
You can use Enum.Parse like, if it is string
AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")
Comparision:
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:
if(userProfile != null)
{
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
}
or shorter version:
if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
//your code
}
You can use extension methods to do the same thing with less code.
public enum AccountType
{
Retailer = 1,
Customer = 2,
Manager = 3,
Employee = 4
}
static class AccountTypeMethods
{
public static bool IsRetailer(this AccountType ac)
{
return ac == AccountType.Retailer;
}
}
And to use:
if (userProfile.AccountType.isRetailer())
{
//your code
}
I would recommend to rename the AccountType to Account. It's not a name convention.
You should convert the string to an enumeration value before comparing.
Enum.TryParse("Retailer", out AccountType accountType);
Then
if (userProfile?.AccountType == accountType)
{
//your code
}

Set MVC3 parameters to default if empty or null in controller

I am struggling to default CId and SId to 1 if the parameters are empty,
public ViewResult Index(int? CId,int?SId,string name,int? p)
{
if (CId == 0 || SId == 0)
{
CId = 1;
SId = 1;
}
Then I will use the values for a normal query. Thanks for any help
Cid and Sid is Nullable, so you can use HasValue property to check if the variable has value or not (null)
public ViewResult Index(int? CId,int?SId,string name,int? p)
{
if (!CId.HasValue || !SId.HasValue)
{
CId = 1;
SId = 1;
}
}
Just curious but have you tried:
public ViewResult Index(string name,int? p,int? CId = 1,int? SId = 1)
{
}
You have to rearrange them, because the default valued parameters have to come last. Also, being that they're nullable, I'm not actually sure if this will work.

Categories

Resources