mvc prevent action link from loop - asp.net

Any idea on how to stop this action link from loop over and over
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Subjects.SubjectName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ScoreName)
</td>
<td>
#Html.DisplayFor(modelItem => item.JanHomework)
</td>
<td>
#Html.DisplayFor(modelItem => item.JanQuiz)
</td>
<td>
#Html.DisplayFor(modelItem => item.JanExam)
</td>
<td>
#Html.DisplayFor(modelItem => item.Result)
</td>
#Html.ActionLink("Edit", "EditScore", new { id = item.SubjectID })
</tr>
}
I have tried to remove the action link from the For-each loop bracket but it will show error, My plan is i want this view to be redirected to another view with the same controller and model.
Current View
public ActionResult Index_Test(int id)
{
List<Term1Score> score = db.Term1Scores.Where(x => x.SubjectID == id).ToList();
return View(score);
}
Redirect to this view
[HttpGet]
public ActionResult EditScore(int id)
{
List<Term1Score> score = db.Term1Scores.Where(x => x.SubjectID == id).ToList();
return View(score);
}

Related

InvalidOperationException while formatting date

I am trying to format my date using .ToString() but I keep getting this error, I understand where it's coming from but I have no idea how to fix it.
The error message I keep getting is: InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Currently my code inside my view looks like this:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.DatePrescribed.ToString("yyyy-MMM-dd hh:mm:ss"))
</td>
<td>
#Html.DisplayFor(modelItem => item.Comments)
</td>
<td>
#Html.DisplayFor(modelItem => item.PatientDiagnosis.PatientDiagnosisId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Treatment.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.PatientTreatmentId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.PatientTreatmentId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.PatientTreatmentId">Delete</a>
</td>
</tr>
}
The line in question is:
#Html.DisplayFor(modelItem => item.DatePrescribed.ToString("yyyy-MMM-dd hh:mm:ss"))
I've been stuck on this for a while so any solution would be much appreciated.
Decorate your property with DisplayFormat like below:
[DisplayFormat(DataFormatString = "{0:yyyy-MMM-dd hh:mm:ss}")]
public DateTime DatePrescribed { get; set; }
And then simply in your view just call property:
#Html.DisplayFor(modelItem => item.DatePrescribed)

How to post values of each item in model from view to controller as a List or Array?

example of view priority list of orders
i have a orders model, i need the user to arrange orders in order of priority by numbers.
for each order a different number of priority and post to the controller the id of the order and the priority number that he selected for the order.
post it to the controller as a list/array of pairs (id, position).
and also how to receive in the actionResult a list/array of value pairs.
this is my PackerController:
public ActionResult SetByCity(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var supplier = db.Suppliers.Where(s => s.Id == id).FirstOrDefault();
var mySupplierOrders = db.Orders.Where(o => o.SupplierId == supplier.Id && o.SupplierApproval == 1).Include(o => o.Clients).Include(o => o.Suppliers);
return View(mySupplierOrders.OrderBy(o => o.Clients.BusinessAddress).ToList());
}
and this is the view for "SetByCity":
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Clients.BusinessName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Clients.BusinessAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreateDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.PayDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Discount)
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalPrice)
</td>
<td>
<form method="post" action="#Url.Action("SetOrdersPosition", "Packer")" id="editform">
<input type="hidden" name="Id" value="#item.Id">
<input type="number" name="Position" min="1" max="#Model.Count()">#*i need to put all the positions and id's of all the items in a pairs list and send it to the controller*#
</form>
</td>
</tr>
}
</table>
<input type="submit" value="send" form="editform" />
and this is the receiving actionResult "SetOrdersPosition" in the PackerController:
[HttpPost]
public ActionResult SetOrdersPosition(List<id,position>)
{
//does something...
}
i don't know what to put in the parameters that the SetOrdersPosition gets...
Hope you are using the Model name called "Suppliers".
So in get method pass that into view.
You needs to do come little changes accordingly to use Begin Form in your view, so that you can directly post your model data to controller.
Use this item inside body.
Don't forget to declare the model which you are using in the view page like below.
#model MVC.Models.Suppliers
#using (Html.BeginForm("SetOrdersPosition", "Packer", FormMethod.Post))
{
<table>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Clients.BusinessName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Clients.BusinessAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreateDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.PayDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Discount)
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalPrice)
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
}
</table>
}
Controller Code [HttpPost]
public ActionResult SetOrdersPosition(Suppliers _suppliers)
{
//does something...
}

I want to sum together values in ASP.NET MVC and display them in razor

I have several costs/fees to display for a tenant and now I want to sum up all the values. Here is my code.
#foreach (var item in Model.Contracts)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Apartment.MonthParkfee)
</td>
<td>
#Html.DisplayFor(modelItem => item.Apartment.MonthUtilityFee)
</td>
<td>
#Html.DisplayFor(modelItem => item.MonthlyRent)
</td>
<td>
#Html.DisplayFor(sumOfAllFees => MonthParkFee + MonthUtilityFee + MonthlyRent)
</td>
</tr>
}
The MonthParkFee and MonthUtilityFee are both in the Apartment table while the MonthlyRent is in the contract table but the contract table contains the foreign key for the Apartment table. How would I be able to add those values together in razor and render them?
Define a variable to hold the sum as below:
#foreach (var item in Model.Contracts)
{
var sum = item.Apartment.MonthParkfee + item.Apartment.MonthUtilityFee +item.MonthlyRent;
<tr>
<td>
#Html.DisplayFor(modelItem => item.Apartment.MonthParkfee)
</td>
<td>
#Html.DisplayFor(modelItem => item.Apartment.MonthUtilityFee)
</td>
<td>
#Html.DisplayFor(modelItem => item.MonthlyRent)
</td>
<td>
#Html.Display("sumOfAllFees" => sum)
</td>
</tr>
}
Or add a Sum property to view model you are sending and send Sum from controller itself to show in the view.

ASP.Net TO SQL Querying

I have the following problem:
Business Problem: I have over 500 ETF's around the world categorized into different types (Region of the world, Capital type (small cap/large cap) etc which are different fields in a SQL database.
Coding Problem: I am able to show the entire list of ETF's, sort them etc. The problem lies in creating 5 different tables (5 regions of the world) on the same web page. In the SQL World it would be a simple
Select * from ETF where RegionDS = 'Europe'
Where I am Today: I am able to query the database and retrieve all the ETF's and show them successfully on the page, but am not able to filter them in any way. Here is the M/V/C for just one table. Hopefully someone can piece it together for me.
MODEL
namespace SmartAdminMvc.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public partial class ETF
{
[Key]
public string Symbol { get; set; }
[Key]
public System.DateTime TodaysDate { get; set; }
public string SubSectorDS { get; set; }
public Nullable<int> RANK { get; set; }
public string RegionDS { get; set; }
VIEW
#model IEnumerable<SmartAdminMvc.Models.ETF>
<table id="dt_basic" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th> #Html.DisplayNameFor(model => model.RANK)</th>
<th> <a title=#Html.DisplayNameFor(model => model.Symbol)> #Html.DisplayNameFor(model => model.Symbol) </a> </th>
<th> <a title=#Html.DisplayNameFor(model => model.TodaysDate)>#Html.DisplayNameFor(model => model.TodaysDate) </a> </th>
<th> <a title=#Html.DisplayNameFor(model => model.SectorDS)>#Html.DisplayNameFor(model => model.SectorDS) </a> </th>
<th> <a title=#Html.DisplayNameFor(model => model.RegionDS)>#Html.DisplayNameFor(model => model.RegionDS) </a> </th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.OrderBy(item => item.RANK).Take(50))
{
if (item.RegionDS == "Europe")
{
<tr>
<td align="right"> #Html.DisplayFor(modelItem => item.RANK) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.Symbol) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.TodaysDate) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.SectorDS) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.RegionDS) </td>
</tr>
}
}
</tbody>
</table>
CONTROLLER:
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using SmartAdminMvc.Models;
namespace SmartAdminMvc.Controllers
{
public class ETFsController : Controller
{
private QlikEntities db = new QlikEntities();
// GET: vDailyPickSummaryTotals
public ActionResult ETFWorld()
{
return View(db.ETFs.ToList());
}
Currently you're taking the top 50 from the whole list, and then trying to filter out by region. But, this will only return the matches in those 50 records, if any. Instead, do the filter first:
<tbody>
#foreach (var item in Model.Where(w => w.RegionDS == "Europe").OrderBy(item => item.RANK).Take(50))
{
<tr>
<td align="right"> #Html.DisplayFor(modelItem => item.RANK) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.Symbol) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.TodaysDate) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.SectorDS) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.RegionDS) </td>
</tr>
}
</tbody>
EDIT:
If you're only displaying a subset of the records you could create a ViewModel such as this:
public class MyViewModel
{
public IEnumerable<ETF> EuropeETFs {get; set;}
public IEnumerable<ETF> AsiaETFs {get; set;}
...
}
Then in your controller:
MyViewModel vm = new MyViewModel();
vm.EuropeETFs = db.ETFs.Where(w => w.RegionDS == "Europe").OrderBy(item => item.RANK).Take(10);
....
Change the model type of your View to MyViewModel, then:
<tbody>
#foreach (var item in Model.EuropeETFs)
{
<tr>
<td align="right"> #Html.DisplayFor(modelItem => item.RANK) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.Symbol) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.TodaysDate) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.SectorDS) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.RegionDS) </td>
</tr>
}
</tbody>

Select multiple data from table in view asp.net MVC4 Razor

i have following View where user has a table of products and i need select all data where "Quantity > 0" default is 0. But i dont know how can i get collection of data from table. Thanks for respond.
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Produkty</legend>
<table>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(model => item.Product.Name)
</td>
<td>
#Html.DisplayFor(model => item.Product.Price)
</td>
<td>
#Html.EditorFor(model => item.Quantity)
</td>
</tr>
}
<p>
<input type="submit" value="Orders" />
</p>
</table>
</fieldset>
}
//Controller
public ActionResult Index()
{
List<ProductListViewModel> productList = new List<ProductListViewModel>();
foreach (var item in db.Products.ToList())
{
ProductListViewModel model = new ProductListViewModel();
model.Product = item;
model.Quantity = 0;
productList.Add(model);
}
return View(productList);
}
Since you're using Html.EditorFor, things are easy.
Put productList as parameter in your Index Action(for Post), MVC will auto combine form data to productList Object, so you just need to filter the quantity in server side with a loop.
Of cause, to identify the product object, you'd better also add a hidden ID in your view.
<table>
#for(int i = 0; i<Model.Count; i++) {
<tr>
<td>
#Html.HiddenFor(model => Model[i].Product.ID)
#Html.DisplayFor(model => Model[i].Product.Name)
</td>
<td>
#Html.EditorFor(model => Model[i].Quantity)
</td>
</tr>
}
[HttpPost]
public ActionResult Index(List<ProductListViewModel> productList)
{
\\...
}

Resources