session's variables values retrieving in _LayoutPartial in asp.net mvc - c#

I'm filling values to a session's like following to retrive those in _LayoutPartial view
if (userdata != null)
{
Session["userdata"] = new SampleViewModel { FirstName = userdata.UserFirstName, LastName = userdata.UserLastName };
FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
return RedirectToAction("Dashboard", "Home", new { username = loginmodel.UserName });
}
I want to retrive those values in _LayoutPartial View , So I tried somethin like following
<a class="sa">
(#Session["userdata"] as ProjectName.Models.SampleViewModel).FirstName
(#Session["userdata"] as ProjectName.Models.SampleViewModel).LastName
</a>
But this is not retrieving data properly . In this _LoginPartial I'm not Referencing any model also

You have your parenthesis in the wrong spot, and you need a double set - one for the casting (inner set) and one for the razor execution (outer set). It needs to be
#((Session["userdata"] as ProjectName.Models.SampleViewModel).Name)

Related

How to pass query parameter value into HTML.Partial model?

I have an MVC page (Not .Net Core) which contains the below code
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(1))
The query in the address bar is similar to ..../products/product?id=4
How could i pass in the query value of 4 (or whatever it might be) into the Model.Product(ID) which then calls some code in my database to retrieve that product?
Using a hardcoded value works so im not sure if i should be doing this differently or if there is a better approach?
Finally hopefully this wont make a difference but once i have this working i would like to change the URL to something more friendly i.e. ..../products/product/4
method 1 : get route data in razor view
{
var id = Context.GetRouteData().Values["id"];
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(id))
method 2 : pass id with controller (viewbag or model)
public ActionResult Product(int id){
var model= {
...
Id = id
}
//ViewBag.Id = id;
return View(model)
}
view:
#model ViewModel
{
var id = int.Parse(ViewBag.Id); // alternative sln.
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(Model.Id))
I have been using the below method and it works for me you can also try this
#Html.Action(, , new { #<Parameter_name> = })
Eg:
#Html.Action("DetailsProducts", "CREDITNOTEs", new { #id = Model.ID })

Not Sure How To Resolve My System.NullReferenceException

I have an Index (List) View in MVC5, that is populated from a model (Table ICS_Supplies).
I have added a textbox to add search filter for the users, on field ItemDescription (varchar). This works perfectly fine as follows:
View
<form asp-controller="Movies" asp-action="Index">
<p>
Search Supplies: <input type="text" name="SearchString">
<input type="submit" value="Filter" />
</p>
</form>
Controller
public ActionResult Index(string searchString, string SType, int? page, string YourRadioButton)
{
// Add SearchBox Filter
var catalogs = supplies.Where(s => s.ItemDescription.Contains(searchString ?? string.Empty));
// Add paging to the search results
var pageNumber = page ?? 1;
return View(catalogs.ToPagedList(pageNumber, 10));
}
This works perfectly. If the searchString is null, it brings back ALL results. IF the searchSring has a value, it brings back any results where ItemDescription Cotain the searchString Value.
I am trying to add a radiobutton to the index view so that the user can also filter on the field InvType, which is a char(1) field. It can be F (for Forms) or S (for supplies). So, I set the value of YourRadioButton to F or S depending on which is selected. . . as follows (with new code)
Index
<form asp-controller="Movies" asp-action="Index">
<div>
Supplies: #Html.RadioButton("YourRadioButton", "S")
Forms: #Html.RadioButton("YourRadioButton", "F")
</div>
<p>
Search Supplies: <input type="text" name="SearchString">
<input type="submit" value="Filter" />
</p>
</form>
And I update the Controller with additional code, as follows:
public ActionResult Index(string searchString, string SType, int? page, string YourRadioButton)
{
var supplies = db.ICS_Supplies.OrderBy(g => g.ItemDescription).ToList();
//var supplies2 = supplies.Where(s => s.InvType.Equals(mychoice));
var supplies2 = supplies.Where(s => s.InvType.Contains(YourRadioButton ?? string.Empty));
// Add SearchBox Filter
var catalogs = supplies2.Where(s => s.ItemDescription.Contains(searchString ?? string.Empty));
// Add paging to the search results
var pageNumber = page ?? 1;
return View(supplies2.ToPagedList(pageNumber, 10));
}
Now, I receive The following error
System.NullReferenceException
And it is referring to the following line of code (which I added)
var supplies2 = supplies.Where(s => s.InvType.Contains(YourRadioButton ?? string.Empty));
My question(s) are . . . Why does that kick out a NullReferenceException, but the other line works perfectly fine if it is null? And how do I resolve the issue - or is there a better way to add this second filter to my code?
This line works fine, null or not. They are both identical in how they are written, other than the Value of YourRadioButton is used, instead of searchString, and I am using InvType field instead of ItemDescription.
var catalogs = supplies2.Where(s => s.ItemDescription.Contains(searchString ?? string.Empty));
Keep in mind that I am VERY new to both MVC5 and C#, and so explaining why would help me a great deal to progress.
There does not seem to be a lot of information out there, in regards to using radio buttons in MVC5 . . . a rather simple concept in old Asp.net forms.
It seems that some entries of suppliers doesn't have an InvType. That property is sometimes null, therefore you receive a NullReferenceException because you are calling Contains() method on a null value property.
The problem doesn't occur in your first example, because you were using Linq to Entities.
In the second example you are calling ToList() after the first query. After that, everything will continue to work in memory (Linq to Objects). Then you have to check for null in any where condition:
var supplies2 = supplies.Where(s => s.InvType != null && s.InvType.Contains(YourRadioButton ?? string.Empty));
I think it is better to remove ToList() from the first query. Add your where conditions to it and let the PagedList execute the query for you:
public ActionResult Index(string searchString, string SType, int? page, string YourRadioButton)
{
var supplies = db.ICS_Supplies.AsQueryable();
if (!String.IsNullOrWhiteSpace(YourRadioButton))
{
supplies = supplies.Where(s => s.InvType.Contains(YourRadioButton));
}
if (!String.IsNullOrWhiteSpace(searchString))
{
supplies = supplies.Where(s => s.ItemDescription.Contains(searchString));
}
supplies = supplies.OrderBy(g => g.ItemDescription)
// Add paging to the search results
var pageNumber = page ?? 1;
return View(supplies.ToPagedList(pageNumber, 10));
}

passing a session variable in link created by for loop C#

I have a page reading an api thats giving a list of ID's.
I then want that to create a link that then sends that ID to another API to get that individual object.
I've got the pages working manually but now trying to send the data between them is the issue.
My current code is this
#{
for (var i = 0; i < Model.records.Count; i++)
{
string currID = Model.records[i].ID;
<td>#Html.ActionLink(Model.records[i].ID, "Game", "Home", Session["game"] = currID)</td>
<td>#Model.records[i].GameName</td>
<td>#Model.records[i].Player1</td>
<td>#Model.records[i].Player2</td>
<td></td><br />
}
}
What this does, And I understand Why, is pass the final record's ID to the api, and always gives me that result, as i is the final value at that point.
how can I tell the link that it needs to keep it's iteration of i and pass that value?
With this expression,
Session["game"] = currID
You are actually updating the Session item value within the loop for each iteration with the current value of currID.
If you want to send the Session item value as querysting/route values, you may use the overload which takes 5 params. The fourth parameter is an anonymous object where you will specify the key and values, these key and values will be used to generate the URL.
For example, the below code will add the gameId querystring item and it's value will be the value stored in Session["game"]
#{
var game = Session["game"];
for (var i = 0; i < Model.records.Count; i++)
{
string currID = Model.records[i].ID;
<td>#Html.ActionLink(Model.records[i].ID, "Game", "Home",
new { gameId = game }, null)</td>
<td>#Model.records[i].GameName</td>
}
}
Assuming your Game action method has a parameter with name gameId
public ActionResult Game(string gameId)
{
// to do : Return something
}
If you want to send the currID as well, pass that too
#Html.ActionLink(Model.records[i].ID, "Game", "Home",
new { gameId = game, currId = currID }, null)
The fifth parameter( where I passed null) is for htmlAttributes which will be used to add other HTML attributes to the element rendered by this helper (Ex : If you want to add a CSS classs etc)

concat string var in razor var name

I can't find anything to solve my problem in search, and here is my problem:
I'm using ASP.NET MVC 4 and EF 5, I'm trying to get a value from my db, but this db field depends on other var.
In Controller:
public ActionResult Products()
{
ViewBag.lang = "ENG";
DataEntities db = new DataEntities();
ViewBag.Categories = db.Categories;
return View();
}
In Template View:
<ul>
#{
if (ViewBag.Categories != null)
{
foreach (var cat in ViewBag.Categories )
{
<!-- we need in this case "Name_ENG" -->
var title = "Name_" + #ViewBag.lang;
<li>#cat.(title)</li>
<!-- out: cat.ToString() + "(title)" -->
<li>#cat.(#title)</li>
<!-- out: cat.ToString() + "(" + title.ToString() + ")" -->
<li>#cat.#title</li>
<!-- out: cat.ToString() + title.ToString() -->
}
}
}
</ul>
is there a way to get property "Name_ENG" from cat object like #cat.Name_ENG using a string ?
"In this case I'm trying to list al Categories in Products page."
Thanks a lot
No, definitely not in c#. You'd have to use reflection for this to work (and the syntax would be different of course as well).
I think a better option would be to create a method that would retrieve the value based on a string input, like
public T GetValue<T>(string propertyName)
and call that from your view when needed
here is an article from msdn. You can access EF entries properties by name. But at first you need dbContext and second it is wrong to access dbContext from view.
example:
object currentName2 = context.Entry(blog).Property("Name").CurrentValue;
Also, as mentioned in another answer, reflection:
object value = typeof(YourType).GetProperty("PropertyName").GetValue(yourInstance, null);
Try this
<ul>
#{
if (ViewBag.Categories != null)
{
foreach (var cat in ViewBag.Categories )
{
// here you can do something on cat
<text>
<li>#(cat.title)</li>
</text>
}
}
}
</ul>
I personally suggest you to pass the data to the view by parameter. And use #model in the view (strong type view).

Object does not contain a definition for Title

I have a controller that passes data to my view through the ViewBag
My controller:
var aJobs = from a in gdb.AcceptedJobs
where a.Job.EmployerID == (Guid)Session["UserID"] && !a.Archived
select new { a.Job.Title, a.Job.Address };
ViewBag.jobs = aJobs;
return View("Employer");
My view:
foreach (var job in ViewBag.jobs)
{
#job.Title
#job.Address
}
Now, when i browse to the page i get error object does not contain a definition for Title, at #job.Title, why is this?
I'm using ASP.Net MVC3 C#
Try creating your anonymous type this way
select new { Title = a.Job.Title, Address = a.Job.Address };
When im debugging, and the error is thrown i checked the locals. Then i can clearly see that in the first iteration, the job-object contains a Title-string with the value of my name.

Categories

Resources