How to pass value from one view to another in MVC? - c#

I would like to display the total amount (#totalAmount) from the index and show it on the payment page which is the next page. I am trying to use a viewbag but it doesn't seem to work.
This is my index...
#model IEnumerable<charity.Models.Donation>
#{
ViewBag.Title = "Index";
ViewBag.total = "#totalAmount";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.DisplayName)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th>
#Html.DisplayNameFor(model => model.Amount)
</th>
<th>
#Html.DisplayNameFor(model => model.TaxBonus)
</th>
<th>
#Html.DisplayNameFor(model => model.Comment)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.DisplayName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Amount)
</td>
<td>
#Html.DisplayFor(modelItem => item.TaxBonus)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comment)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
#{
Decimal totalAmount = 0;
if (Model != null)
{
totalAmount = Model.Sum(x => x.Amount);
}
<label>Total amount donated</label>
<h1 id="amount">#totalAmount</h1>
}
#{
Decimal totaltax = 0;
if (Model != null)
{
totaltax = Model.Sum(x => x.TaxBonus);
}
<label>Total tax bonus</label>
<h1 name="amount">#totaltax</h1>
}
This is my payment page...
#{
ViewBag.Title = "Payment";
}
<h2>Payment</h2>
<form>
<h1>#ViewBag.total</h1>
</form>
Index and payment code from the controller...
public ActionResult Index()
{
return View(db.Donations.ToList());
}
public ActionResult Payment() {
return View();
}

Try to use a Session Variable instead of your ViewBag.
It will store the total as an int.
Session["totalAmount"] = Model.Sum(x => x.Amount);

Related

delete, edit, and details for a user in admin controller MVC 5

In my app, I am trying to add create, edit, delete, and details actions.
the Create action seems working just fine. However, in the delete action I have the following:
[HttpPost]
public async Task<ActionResult> DeleteAspUsers(string id)
{
//this is the users model
AspUsers users = new AspUsers();
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
IdentityUser theUser = new IdentityUser() { Id = users.ID };
theUser = userManager.FindById(theUser.Id);
if (theUser != null)
{
IdentityResult result = await userManager.DeleteAsync(theUser);
}
else
{
ModelState.AddModelError("", "user was not found");
}
return RedirectToAction ("GetAllUsers/");
}
and the view for getting all users in a table as the following:
#model IEnumerable<IdentityUser>
#using Microsoft.AspNet.Identity.EntityFramework;
#using Microsoft.AspNet.Identity.Owin;
#using Microsoft.AspNet.Identity;
#using RidesApp.Controllers;
#using RidesApp.Models;
#{
ViewBag.Title = "GetAllUsers";
Layout = "~/Views/Shared/AdminsLayout.cshtml";
}
<h2>GetAllUsers</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.EmailConfirmed)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNumberConfirmed)
</th>
<th>
#Html.DisplayNameFor(model => model.TwoFactorEnabled)
</th>
<th>
#Html.DisplayNameFor(model => model.LockoutEndDateUtc)
</th>
<th>
#Html.DisplayNameFor(model => model.LockoutEnabled)
</th>
<th>
#Html.DisplayNameFor(model => model.AccessFailedCount)
</th>
<th>
#Html.DisplayNameFor(model => model.UserName)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmailConfirmed)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNumberConfirmed)
</td>
<td>
#Html.DisplayFor(modelItem => item.TwoFactorEnabled)
</td>
<td>
#Html.DisplayFor(modelItem => item.LockoutEndDateUtc)
</td>
<td>
#Html.DisplayFor(modelItem => item.LockoutEnabled)
</td>
<td>
#Html.DisplayFor(modelItem => item.AccessFailedCount)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "DeleteAspUsers", new {id= item.Id})
</td>
</tr>
}
</table>
I was trying to use the " AspUsers" model that I have but I got an error, so I tried to use the (#model IEnumerable ) and that worked. However, when I click delete I'm getting a "404" error that it wasn't found.
I was generally use my own dtatbase (connecting it from an sql server). I added the Identity to an existing application.
So, basically I have my own tables for the users but now I have the aspnetUsers and other tables which was generated after adding the identity framework. this is my current tables:
I'm Also wondering how would I generate the edit and display the users details in the "details" action.
I would appreciate any help. Thank you.
try using
return RedirectToAction ("GetAllUsers");
instead of
return RedirectToAction ("GetAllUsers/");

When I run my page it returns an error of null as if it is not capturing the information passed in

I am creating a project called trash collector, from the Employee Controller, they will be able to confirm that a trash pickup was done and a charge amount will be added to the customer.
I created the logic below in the Employee Controller and created a button in the Index View to capture that confirmed pickup is now true and to add charge amount. It is capturing the charge amount, but it is not able to find my customer.
I'm getting an Error:
"Object reference not set to an instance of an object"
Customer is null. I am not sure why it is showing as null because in the Index Logic I set it up for it to find Customers within the Zipcode of the Employee and it came back fine, but for the ConfirmPickup logic Customer is coming back as null, it is also showing that same error for my edit actionlink and details actionlink.
Employee Controller
Method below works and is bringing back customers:
public ActionResult Index(string searchBy, string search)
{
var UserId = User.Identity.GetUserId();
Employee employee = db.Employees.Where(e => e.ApplicationId == UserId).FirstOrDefault();
var filteredCustomer = db.Customers.Where(c => c.ZipCode == employee.ZipCode && c.PickupDay == DateTime.Today.DayOfWeek.ToString() && c.ConfirmPickedup == false);
if (searchBy == "Pickup Day")
{
return View(db.Customers.Where(c => c.PickupDay == search && c.ZipCode == employee.ZipCode).ToList());
}
return View(filteredCustomer);
}
Method below does not work:
PickupConfirmed(Customer customer) is returns null. I have tried a try, catch still it returns null.
public ActionResult PickupConfirmed(Customer customer)
{
//var UserId = User.Identity.GetUserId();
var pickupConfirmedCustomer = db.Customers.Find(customer.Id);
pickupConfirmedCustomer.AccountBalance += 19.99;
pickupConfirmedCustomer.ConfirmPickedup = true;
db.SaveChanges();
return RedirectToAction("Index");
}
Here is my Index View:
#model IEnumerable<Trash_Collector.project.Models.Customer>
#{
ViewBag.Title = "Index";
}
<h2>Pickups For Today</h2>
<p>
#using (Html.BeginForm("Index", "Employees", FormMethod.Get))
{
<b>Search By:</b> #Html.RadioButton("searchBy", "Pickup Day", true) <text>Pickup Day</text>
#Html.TextBox("search") <input type="submit" value="Search" />
}
</p>
#using (Html.BeginForm("PickupConfirmed", "Employees", FormMethod.Get))
{
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.StreetAddress)
</th>
<th>
#Html.DisplayNameFor(model => model.City)
</th>
<th>
#Html.DisplayNameFor(model => model.State)
</th>
<th>
#Html.DisplayNameFor(model => model.ZipCode)
</th>
<th>
#Html.DisplayNameFor(model => model.PickupDay)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.StreetAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
#Html.DisplayFor(modelItem => item.ZipCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.PickupDay)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
<td>
<input type="submit" value="Confirm Pickup" />
</td>
</tr>
}
</table>
}
Your code
var filteredCustomer = db.Customers.Where(c => c.ZipCode == employee.ZipCode && c.PickupDay == DateTime.Today.DayOfWeek.ToString() && c.ConfirmPickedup == false);
change code
var filteredCustomer = db.Customers.Where(c => c.ZipCode == employee.ZipCode && c.ConfirmPickedup == false);
Maybe this portion is a problem
c.PickupDay == DateTime.Today.DayOfWeek.ToString() //is not equal

ASP.NET MVC Two models in ove view, code change

I had this code and it worked fine:
#model IEnumerable<Moviestore.Models.Movie>
#{
ViewBag.Title = "Index";
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.Author)
</th>
<th>
#Html.DisplayNameFor(model => model.Year)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Year)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
#Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
</td>
</tr>
}
}
</table>
But I needed to add one more model, I done that with Tuple In this way:
#using Moviestore.Models;
#model Tuple<Movie, User>
#{
ViewBag.Title = "Index";
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(tuple => tuple.Item1.Title)
</th>
<th>
#Html.DisplayNameFor(tuple => tuple.Item1.Genre)
</th>
<th>
#Html.DisplayNameFor(tuple => tuple.Item1.Author)
</th>
<th>
#Html.DisplayNameFor(tuple => tuple.Item1.Year)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Year)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
#Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
</td>
</tr>
}
}
</table>
But now I have problem with bottom half of code.
From #foreach
I don't know what I need to put instead of #foreach (var item in Model)
And will then #Html.DisplayFor(modelItem => item.Title) also need some changes.
Sorry for long post, I tried to explain the problem as best as I can.
As I mentioned in the comments, the appropriate way to handle this situation (needing more than one model on a particular View page) is to use a ViewModel which contains the models you need (see here for reference).
To answer your specific question, though, you can access each item of the Tuple by its position, e.g. if your model is Tuple<Movie, User>, then you can access the Movie object by model.Item1 and the User object by model.Item2, etc.
But I strongly recommend you take the ViewModel approach that I linked instead.
Hi here is the viewmodel for your requirement:
public class MovieUserViewModel
{
public IEnumerable<Movie> Movie { get; set; }
public IEnumerable<Users> Users { get; set; }
}
With the above viewmodel , you can easily access each class
#foreach (var item in Model.Movie)
#foreach (var item in Model.Users)
Additional info : Understanding ViewModel in ASP.NET MVC
Thanks
Karthik

How to check if View has received no results

Sorry I didn't really know how to title this.
I have a webpage that displays announcements. What I cant seemed to figure out is whether there are any announcements, if there are display saying "There are no announcements".
I've tried stuff like:
if(db.Announcements.toArray().length == 0){
return View(null);
}
but that doesn't work. Where do I deal with things like these? View/Controller?
View:
#model IEnumerable<Remake.Models.Announcement>
#{
ViewBag.Title = "Announcements";
}
<h2>Announcements</h2>
#if (User.Identity.IsAuthenticated)
{ <p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
<b> #Html.DisplayNameFor(model => model.Title)</b>
</th>
<th>
#Html.DisplayNameFor(model => model.Content)
</th>
<th width="10%">
#Html.DisplayName("Date")
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<b> #Html.DisplayFor(modelItem => item.Title)</b>
</td>
<td>
#Html.DisplayFor(modelItem => item.Content)
</td>
<td>
<b>#Html.DisplayFor(modelItem => item.PostDate)</b>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.AnnouncementId }) |
#Html.ActionLink("Comments", "Details", new { id = item.AnnouncementId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.AnnouncementId })
</td>
</tr>
}
</table>
}
else
{
<p>Please sign in to create an Announcement</p>
}
Controller:
// GET: Announcements
public ActionResult Index()
{
return View(db.Announcements.ToList());
}
Since your model is defined as IEnumerable<Announcement>, you can simply use Any() to check whether it's empty or not:
#if (Model.Any())
{
// show announcements
foreach (var item in Model)
{
// ...
}
}
else
{
// show message when empty
<p>No announcements</p>
}
See MSDN

Show the result of an int method in the Index View

I`ve made a simple method to count how many Albums do I have in a table, my only question is simple, I want to show the result of the Count method in the AlbumIndex view. Lets say I want to show a label: "Total" and the number besides it, how do I do this in the View?
This is the method(inside a class called Operations, separated from Controllers and Models):
public int AlbumCounter()
{
int x = db.Albums.Count();
return x;
}
This is the ActionResult Method in my AlbumsController(I don`t know what to do, I want to show the result in the Index View)
public ActionResult AlbumCounter()
{
return
}
and here is the Index View:
#model IEnumerable<AlexMusicStore.Models.Album>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Artist.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.AlbumName)
</th>
<th>
#Html.DisplayNameFor(model => model.DateCreated)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Artist.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.AlbumName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.AlbumID }) |
#Html.ActionLink("Details", "Details", new { id=item.AlbumID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.AlbumID })
</td>
</tr>
}
</table>

Categories