ASP.Net TO SQL Querying - asp.net

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>

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...
}

mvc prevent action link from loop

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);
}

IEnumerable View returning null on HttpPost

I have a Form which is filled with some grid like structure with CheckBoxes and DisplayField.
I want to fetch rows with Checked CheckBoxes. Problem is i am getting null in Controller's post method.
Models
public class RegisterModuleSelection
{
[Display(Name = "ID")]
public int mID { get; set; }
[Display(Name = "Module")]
public string Module { get; set; }
[Display(Name = "Buy")]
public bool Buy { get; set; }
}
View
#model IEnumerable<MAK_ERP.Models.RegisterModuleSelection>
#{
ViewBag.Title = "Register - Modules Selection";}
<h2>
Register - Modules Selection</h2>
#using (Html.BeginForm("RegisterModules", "UserAccount", FormMethod.Post, new { id = "RegisterModules", #class = "generalForm" }))
{
<table class="Grid Module">
<tr>
<th>
#Html.DisplayNameFor(model => model.Module)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
#Html.DisplayNameFor(model => model.Duration) (Months)
</th>
<th>
#Html.DisplayNameFor(model => model.Buy)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.HiddenFor(modelItem => item.mID)
#Html.DisplayFor(modelItem => item.Module)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.EditorFor(modelItem => item.Duration)
</td>
<td>
#Html.CheckBoxFor(modelItem => item.Buy)
</td>
</tr>
}
<tr>
<td colspan="4">
<input type="submit" value="Next" class="button3" />
<input type="reset" value="Reset" class="button4" />
</td>
</tr>
</table>
}
Controller
[HttpGet]
public ActionResult RegisterModules()
{
IEnumerable<MAK_ERP.Models.RegisterModuleSelection> model = reg.getModules();
return View(model);
}
[HttpPost]
public ActionResult RegisterModules(IEnumerable<Models.RegisterModuleSelection> regMod)
{
//regMod is null here
...
Unfortunately you cannot bind in this way. Model binding depends upon how generated html looks like. In this particular case it should look something like:
<input id="item_Buy" type="checkbox" value="true" name="item[0].Buy" checked="checked">
If you are okay with some workarounds, you can use a for loop instead of foreach loop where you can add an index to each control name and model binder could bind them properly.
There are some really helpful discussions available, you can check here: ASP.NET MVC - Insert or Update view with IEnumerable model. And also Model Binding To A List. Another one is: Modelbinding IEnumerable in ASP.NET MVC POST?
You should use EditorTemplates to solve the problem.
The accepted answer at ASP.NET MVC Multiple Checkboxes would help you.

How to get table data from view is asp.net mvc 4

My question is how to get table data back to the controller from view?
I have class in my model:
public class Company
{
public string Name { get; set; }
public int ID { get; set; }
public string Address { get; set; }
public string Town { get; set; }
}
and I pass list of Companies to my view as:
#model IEnumerable<MyTestApp.Web.Models.Company>
....
#using (Html.BeginForm("Edit", "Shop"))
{
<table id="example">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Town)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.EditorFor(modelItem => item.Name)
</td>
<td>
#Html.EditorFor(modelItem => item.Address)
</td>
<td>
#Html.EditorFor(modelItem => item.Town)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Submit" />
}
And everything looks ok, but I can't understand how to get modified data in the controller? I used these approaches:
public ActionResult Edit(IEnumerable<Company> companies)
{
// but companies is null
// and ViewData.Model also is null
return RedirectToAction("SampleList");
}
I need access to modified objects, what am I doing wrong?
UPDATE: Thanks to webdeveloper, I just needed use 'for' loop instead of 'foreach' loop. Right version is
<tbody>
#for (int i = 0; i < Model.Count(); i++ ) {
<tr>
<td>
#Html.EditorFor(modelItem => modelItem[i].Name)
</td>
<td>
#Html.EditorFor(modelItem => modelItem[i].Address)
</td>
<td>
#Html.EditorFor(modelItem => modelItem[i].Town)
</td>
</tr>
}
</tbody>
Please, look at my answer here: Updating multiple items within same view OR for Darin Dimitrov answer.
You need items with index in name attribute in rendered html markup. Also you could look at: Model Binding To A List
I think that you are missing the Company's ID in your form so that the model can be correctly bound.
You should add it like this:
#using (Html.BeginForm("Edit", "Shop"))
{
<table id="example">
<thead>
<tr>
<th>
#Html.HiddenFor(model => model.ID)
#Html.DisplayNameFor(model => model.Name)
</th>
...
Otherwise the rest of your code seems to be OK.
You need to bind your table rows by providing an id for each one being edited so mvc can bind to it back to the controller. One row of table data example:
#for (var a = 0; a < #Model.Pets.Count; a++)
{
<tr>
<td>
#Html.CheckBoxFor(model => #Model.Pets[a].ChildSelected, new { #id= a + "childSelected" })
</td>
</tr>

Resources