ASP MVC4 - Pass List to view via view model - c#

I have a model Person (with among other fields the day of Birth)
and I want to pass a list of all persons, together with the calculated age of each person, to the view
Therefor:
The view model
public class vm_PersonList
{
public Person Person { get; set; }
public int age { get; set; }
}
The controller action:
public ActionResult PersonList()
{
ViewBag.Message = "My List";
var list = new List<vm_PersonList>();
var list_p = new vm_PersonList();
foreach (var p in db.Person)
{
list_p.Person = p;
//the age will be calculated based on p.birthDay, not relevant for the
//current question
list_p.age = 23;
list.Add(list_p);
}
return View(list);
}
The view
#model List<programname.Viewmodels.vm_PersonList>
#foreach (var p in Model)
{
<tr>
<td>
#p.Person.FullName
</td>
<td>
#p.age
</td>
</tr>
}
The Person table contains for example 6 entries.
When debugging the application I see:
At the end of the controller action "list" contains correctly the 6 different Person entries
In the view, the "Model" contains 6 entries, but 6 times the last "database entry".
Does anyone have a suggestion to solve this issue?

You are using the same list_p instance over and over again inside the loop. So you are constantly updating its Person property. And since Person is a reference type you are modifying the same reference in memory. At the last iteration of the loop you are obviously replacing this reference with the last instance of Person which explains why you are seeing the same person in the view.
Try like this, seems lot easier:
public ActionResult PersonList()
{
ViewBag.Message = "My List";
var model = db.Person.Select(p => new vm_PersonList
{
Person = p,
age = 23
}).ToList();
return View(model);
}

You are working on the same instance of vm_PersonList. Move the instantiation of vm_PersonList into the loop
foreach (var p in db.Person)
{
var list_p = new vm_PersonList();
list_p.Person = p;
//the age will be calculated based on p.birthDay, not relevant for the
//current question
list_p.age = 23;
list.Add(list_p);
}

It's an issue with the scope of your list_p instance. Try changing your controller code to:
public ActionResult PersonList()
{
ViewBag.Message = "My List";
var list = db.Person
.Select(p => new vm_PersonList
{
Person = p,
age = 23,
})
.ToList();
return View(list);
}

Related

How to call View method and pass parameter to method?

I have a list of categories in the Sidebar.
#foreach (var item in Model) {
<li>#item.Title</li>
}
And I want to display the products of this category by clicking on the category. To do this, I implemented the method ViewCategory.
public ActionResult ViewCategory(string name) { ... }
But I do not know how to pass the parameter correctly. I'm trying to write something like that, but I understand that doing something wrong ...
#Html.Action("ViewCategory", "Books", new {Title=item.Title})
Help me please
UPDATE
I have a View Index, and a method in which I bring up a list of my products
public ActionResult Index()
{
HttpResponseMessage response = WebApiClient.GetAsync("Books").Result;
var booksList = response.Content.ReadAsAsync<IEnumerable<BookDto>>().Result;
return View(booksList);
}
I need to display only products that belong to this category when choosing a category. I list the categories with PartialView
<ul>
#foreach (var item in Model) {
#*<li></li>*#
#Html.Action("ViewCategory", "Books", new { name = item.Title })
}
To do this, I wrote a method that I try to use instead of
public ActionResult ViewCategory(string name)
{
HttpResponseMessage responseBooks = WebApiClient.GetAsync("Books").Result;
List<BookDto> booksList = responseBooks.Content.ReadAsAsync<IEnumerable<BookDto>>().Result.ToList();
for (int i = 0; i < booksList.Count; i++)
{
if (booksList[i].CategoryName != name)
{
booksList.Remove(booksList[i]);
}
}
return View("Category");
}
But now I have NullReferenceException...
Just change
#Html.Action("ViewCategory", "Books", new {Title=item.Title})
to
#Html.Action("ViewCategory", "Books", new {name = item.Title})
You can use it as following.
#{ Html.RenderAction("ViewCategory", "Books",
new {param1 = "value1", param2 = "value2" }); }
You can try using
#Html.Action("Controller","Name", new { name = item.Title })

ASP EF Increment / Decrement Value with + / - buttons

So I'm new to ASP and EF and I am wondering how to do this incredibly basic operation, as well as a few questions to go along with doing it.
Currently I have a table we will call Resource;
class Resource
{
int current;
int min;
int max;
};
Right now I have the default CRUD options for this. What I would like is a + / - button on the main list that will manipulate the current value of each resource and update the value in the DB and on screen.
There are also certain operations I'd like to run such as "AddFive" to a selected group of resources.
So my questions;
How do I do this?
Is this scalable? If someone is constantly hitting the buttons this is obviously going to send a lot of requests to my DB. Is there any way to limit the impact of this?
What are my alternatives?
Thanks.
Edit:
To clarify the question; here are my post functions. How / where do I add these in my view to get a button showing for each resource. I just want the action to fire and refresh the value rather than redirect to a new page.
#Html.ActionLink("+", "Increment", new { id = item.ID })
public void Increment(int? id)
{
if (id != null)
{
Movie movie = db.Movies.Find(id);
if (movie != null)
{
Increment(movie);
}
}
}
[HttpPost, ActionName("Increment")]
[ValidateAntiForgeryToken]
public ActionResult Increment([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Resource resource)
{
if ((resource.Current + 1) < (resource.Max))
resource.Current++;
return View(resource);
}
It sounds like the main issue you are having is creating a list of movies on the front end and updating the details for a specific one.
The key here is that you will need to either wrap a form around each item and have that posting to your update controller or use ajax / jquery to call the controller instead.
I have given you an example of the first one. Once the update controller is hit it will redirect to the listing page which will then present the updated list of movies.
Below is a minimal working example of how to wire this up. I've not included any data access code for brevity but have included psuedo code in the comments to show you where to place it.
Please let me know if you have any futher questions.
Controller
public class MoviesController : Controller
{
public ViewResult Index()
{
// Data access and mapping of domain to vm entities here.
var movieListModel = new MovieListModel();
return View(movieListModel);
}
public ActionResult Increment(IncrementMovieCountModel model)
{
// Put breakpoint here and you can check the value are correct
var incrementValue = model.IncrementValue;
var movieId = model.MovieId;
// Update movie using entity framework here
// var movie = db.Movies.Find(id);
// movie.Number = movie.Number + model.IncrementValue;
// db.Movies.Save(movie);
// Now we have updated the movie we can go back to the index to list them out with incremented number
return RedirectToAction("Index");
}
}
View
#model WebApplication1.Models.MovieListModel
#{
ViewBag.Title = "Index";
}
<h2>Some Movies</h2>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Increment Value</td>
<td></td>
</tr>
#foreach (var movie in Model.MovieList)
{
using (Html.BeginForm("Increment", "Movies", FormMethod.Post))
{
<tr>
<td>#movie.Id #Html.Hidden("MovieId", movie.Id)</td>
<td>#movie.Name</td>
<td>#Html.TextBox("IncrementValue", movie.IncrementValue)</td>
<td><input type="submit" name="Update Movie"/></td>
</tr>
}
}
</table>
Models
public class MovieListModel
{
public MovieListModel()
{
MovieList = new List<MovieModel> {new MovieModel{Id=1,Name = "Apocalypse Now",IncrementValue = 3}, new MovieModel {Id = 2,Name = "Three Lions", IncrementValue = 7} };
}
public List<MovieModel> MovieList { get; set; }
}
public class MovieModel
{
public int Id { get; set; }
public string Name { get; set; }
public int IncrementValue { get; set; }
}
public class IncrementMovieCountModel
{
public int IncrementValue { get; set; }
public int MovieId { get; set; }
}

mvc 4 drop down default value selected

I want to select the default value in drop down list where policyId = 7 but it didn't select that value, what i am doing wrong?
Controller:
var pm = new ManagerClass();
IEnumerable<myClass> po = pm.GetDataFromDb();
IEnumerable<SelectListItem> Policies = new SelectList(po, "PolicyID", "PolicyName", new { PolicyID = 7 });
ViewBag.Policies = Policies;
View:
#Html.DropDownListFor(m => m.PolicyID, ViewBag.Policies as IEnumerable<SelectListItem>, new { #class = "dropdown-field"})
It's because it's not actually selecting the value in the SelectList.
First, to make it nicer, put the items in your view model to prevent the cast (this is better practice too):
public class MyModel
{
public int PolicyID { get; set; }
public List<SelectListItem> Policies { get; set; }
//rest of your model
}
Then populate it:
var model = new MyModel();
model.Policies = po
.Select(p => new SelectListItem
{
Text = p.PolicyName,
Value = p.PolicyID.ToString(),
Selected = p.PolicyID == currentPolicyId //change that to whatever current is
})
.ToList();
Then in your view, do:
#Html.DropDownListFor(m => m.PolicyID, Model.Policies, new { #class = "dropdown-field"})
Just set the PolicyID property on your view model to the value you want to be preselected:
var pm = new ManagerClass();
var po = pm.GetDataFromDb();
ViewBag.Policies = new SelectList(po, "PolicyID", "PolicyName");
viewModel.PolicyID = 7;
return View(viewModel);
Since your DropDownList is bound to the PolicyID property (m => m.PolicyID), then its value will be used when deciding which element to be preselected.
In case that you have a static menu:
1- create the following class:
public static class StaticMenus
{
public static List<string> GetGridRowsCount()
{
List<string> result = new List<string>();
result.Add("3");
result.Add("5");
result.Add("10");
result.Add("20");
result.Add("25");
result.Add("50");
result.Add("100");
return result;
}
}
2- add the following code to your controller :
ViewData["CountryList"] = new SelectList(StaticMenus.GetGridRowsCount(),"10");
3- add the following code to your view:
#Html.DropDownList("MainGridRowsCount", ViewData["RowsCountList"] as SelectList)

Set selected value in dropdown list

How do I set the selected value on a drop down list? Here is what I have so far:
#model Web.Models.PostGraduateModels.PlannedSpecialty
#Html.DropDownList("PlannedSpecialtyID")
//controller
[HttpGet]
public PartialViewResult PlannedSpecialty()
{
// Get Planned Specialty ID
var pgtservice = new PgtService();
PostGraduateModels.PlannedSpecialty plannedSpecialty = pgtservice.GetPlannedSpecialtyId();
// Get Data for Planned Specialty DropDown List from SpecialtyLookup
var pgtServ = new PgtService();
var items = pgtServ.GetPlannedSpecialtyDropDownItems();
ViewBag.PlannedSpecialtyId = items;
return PartialView(plannedSpecialty);
}
// service
public IEnumerable<SelectListItem> GetPlannedSpecialtyDropDownItems ()
{
using (var db = Step3Provider.CreateInstance())
{
var specialtyList = db.GetPlannedSpecialtyDdlItems();
return specialtyList;
}
}
// data access
public IEnumerable<SelectListItem> GetPlannedSpecialtyDdlItems()
{
IEnumerable<Specialty> specialties = this._context.Specialties().GetAll();
var selList = new List<SelectListItem>();
foreach (var item in specialties)
{
var tempps = new SelectListItem()
{
Text = item.Description,
Value = item.Id.ToString()
};
selList.Add(tempps);
}
return selList;
}
I would recommend you to avoid using ViewBag/ViewData/ Weekly typed code. Use strongly typed code and it makes it more readable. Do not use the Magic strings/ Magic variables. I would add a collection property to your ViewModel to hold the SelectList items and another property to hold the selected item value.
public class PlannedSpecialty
{
public IEnumerable<SelectListItem> SpecialtyItems { set;get;}
public int SelectedSpeciality { set;get;}
//Other Properties
}
and in your Get action, If you want to set some Item as selected,
public PartialViewResult PlannedSpecialty()
{
var pgtServ = new PgtService();
var vm=new PlannedSpecialty();
vm.SpecialtyItems = pgtServ.GetPlannedSpecialtyDropDownItems();
//just hard coding for demo. you may get the value from some source.
vm.SelectedSpeciality=25;// here you are setting the selected value.
return View(vm);
}
Now in the View, use the Html.DropDownListFor helper method
#Html.DropDownListFor(x=>x.SelectedSpeciality,Model.SpecialtyItems,"select one ")
Use the selected property of the SelectListItem class:
selList.Selected = true;

Trying to pass a parameter but getting a "context" error

I am trying to pass this from my controller into my view (#ViewBag.Chapter7Total):
ViewBag.Chapter7Total = calc.CalculatePrice(quoteData, Chapter7);
But am getting a "doesn't exist in the current context error" in VS.
Basically, I am trying to pass in a second parameter which determines which pricing structure to use between 2. Chapter7 or Chapter13, with the selection determining the second parameter to perform calculations with.
Here are my methods:
class Chapter
{
public decimal PaymentPlan { get; set; }
public decimal Price { get; set; }
}
public decimal decPaymentPlan(QuoteData quoteData, Chapter chapter)
{
if (quoteData.StepFilingInformation.PaymentPlanRadioButton
== StepFilingInformation.PaymentPlan.No)
return PriceQuote.priceNoPaymentPlan;
else
return chapter.PaymentPlan;
}
public decimal Calculate(QuoteData quoteData, Chapter chapter)
{
decimal total = chapter.Price;
total += this.decPaymentPlan(quoteData, chapter);
return total;
}
static Chapter Chapter7 = new Chapter() { Price = 799.00m, PaymentPlan = 100.00m };
Finally, this is my controller:
public ActionResult EMailQuote()
{
Calculations calc = new Calculations();
Chapter chap = new Chapter();
QuoteData quoteData = new QuoteData
{
StepFilingInformation = new Models.StepFilingInformation
{
//just moking user input here temporarily to test out the UI
PaymentPlanRadioButton = Models.StepFilingInformation.PaymentPlan.Yes,
}
};
var total = calc.CalculatePrice(quoteData);
ViewBag.Chapter7Total = calc.CalculatePrice(quoteData, Chapter7);
return View(quoteData);
}
I'm not sure what to do to pass Chapter7. Any thoughts?
UPDATE 1:
This is my ViewModel (QuoteData):
public class QuoteData
{
public PriceQuote priceQuote;
public Calculations calculations;
public StepFilingInformation stepFilingInformation { get; set; }
public QuoteData()
{
PriceQuote = new PriceQuote();
Calculations = new Calculations();
}
}
I'm trying to figure out what you are doing here but I see that most importantly, you are sending quoteData to your View. I'm making a guess here but I figure QuoteData is a custom entity type of yours and not a ViewModel.
To start, I would create a QuoteDataViewModel in your models with all the properties of QuoteData that you need, including
public class QuoteDataViewModel {
... all of your quoteData properties here
public Chapter Chapter7 { get; set; }
}
In your EMailQuote action, something similar to this
public ActionResult EMailQuote() {
...
var model = new QuoteDataViewModel();
var quoteData = new QuoteData();
... // map your quoteData to your model with Automapper or manually like
... // model.SomeProperty = quoteData.SomeProperty;
... // repeat for all properties
model.Chapter7 = Chapter7;
return View(model);
}
If you are posting this data back you would need your Post action to accept the new QuoteDataViewModel
public ActionResult EmailQuote(QuoteDataViewModel model) {
if(ModelState.IsValid) {
....//save data that was entered?
}
return View(model);
}
Your view would then take a QuoteDateViewModel
#model QuoteDataViewModel
This is all just how I would do it personally, I don't quite understand what you have going on, for example, this line:
var total = calc.CalculatePrice(quoteData);
I don't see total ever being used after you create it.
Anyway, that's just a sample of how I'd do it, create a model specific to the view, include any and all properties I need, populate the model in the controller and send it to the view
Update
Based on the OP comment that quoteData is a ViewModel, then just as above, adding the new property to hold the extra data is simple, by adding ...
public decimal QuoteTotal { get; set; }
public Chapter Chapter7 { get; set; }
...to the ViewModel
the controller populates
var total = calc.CalculatePrice(quoteData);
model.QuoteTotal = total;
model.Chapter7 = new Chapter();
model.Chapter7 = Chapter7;
In the View the values can be accessed like:
#Html.DisplayFor(model => model.QuoteTotal)
#Html.DisplayFor(model => model.Chapter7.PaymentPlan)
#Html.DisplayFor(model => model.Chapter7.Price)

Categories