Pager in .Net Core 2.1 - c#

I have added ReflectionIT.Mvc.Paging from NuGet Link but I have a problem.
In a controller i have 2 methods, Index and Organizations. When I am on the view of Orginizations and press page with number "2" in controller goes to index and not on Organizations method.
How to force it to go on a method I want or to extend this #await this.Component.InvokeAsync("Pager", new { pagingList = this.Model }) to pass method name as parameter?
Controller:
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> Organizations(int page=1)
{
var userlist = _context.Users.Include(u => u.UserRoles).ThenInclude(u => u.Role).Where(o => o.UserRoles.All(r => r.Role.Name == "Company") && o.IsActive == true).AsNoTracking().OrderByDescending(o => o.Company);
var model = await PagingList.CreateAsync(userlist, 2, page);
return View(model);
}
View:
#model ReflectionIT.Mvc.Paging.PagingList<CharityProject.Models.ApplicationUser>
#using ReflectionIT.Mvc.Paging
#addTagHelper *, ReflectionIT.Mvc.Paging
#{
ViewData["Title"] = "Organizations";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container py-lg-5 py-md-5 py-sm-4 py-4">
<h2 class="pageTitles">Organizations</h2>
<div class="row">
<nav aria-label="NewsFeed navigation example">
#await this.Component.InvokeAsync("Pager", new { pagingList = this.Model })
</nav>
<br />
#foreach (var item in Model)
{
<div class="col-lg-4 col-md-6 col-sm-6 product-men women_two">
<div class="product-toys-info">
<div class="men-pro-item">
<div class="men-thumb-item">
#if (item.Logo != null)
{
<img src=#Url.Content(item.Logo.Replace("//","/").Replace("///","/")) class="img-thumbnail img-fluid" alt="">
}
<div class="men-cart-pro">
<div class="inner-men-cart-pro">
View
</div>
</div>
</div>
<div class="item-info-product">
<div class="info-product-price">
<div class="grid_meta">
<div class="product_price">
<h4>
<a href=#Url.Action("OrganizationInfo","Home",new { id=item.Id})>#item.Company</a>
</h4>
<p>#item.Moto</p>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
}
<br />
<nav aria-label="NewsFeeds navigation example">
<vc:pager paging-list="#Model" />
</nav>
</div>
</div>

You can set the Action property to PagingList object :
var model = await PagingList.CreateAsync(userlist, 2, page);
model.Action = "Organizations";

Related

Unable to bind data to the razor view even though the model is not null

Even though the model is not null the required html is not rendered. This is my razor view:
#model List<Product>
#{
ViewBag.Title = "Cart";
}
#for(int i=0;i<=Model.Count()-1;i++)
{
<p>foreach triggered</p>
var image = "~/images/" + Model[i].product_image_path;
<div class="row">
<div class="col">
<div class="row">
<div class="col-md-2">
<img src="#image" alt="No image" class="img-fluid" width="60" asp-append-version="true" />
</div>
<div class="col-md-4">
<div class="row">
<div class="col">
<p class="justify-content-md-start">#Model[i].ProductName</p>
</div>
</div>
<div class="row">
<div class="col">
<p>₹#Model[i].Price</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-8">
#*change quantity button*#
<div class="input-group">
<button type="submit" class="btn btn-light"> - </button>
<input type="text" class="form-control" value="#Model[i].Quantity" readonly />
<button type="submit" class="btn btn-light"> + </button>
</div>
</div>
</div>
<br />
</div>
<div class="col-md-2">
<div class="row">
<div class="col">
<button class="btn btn-danger" type="button" id="button-minus">Remove</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Here is my get action method. This is basically retrieving the product from the models. I am returning an object of List<Product>. Trying to loop over it using for loop on razor view does not seem to work.
[HttpGet]
public IActionResult Cart()
{
var model = new CartProductViewModel();
var sessionId = HttpContext.Session.Id;
var allCartItems = context.cartItems;
var allProducts = context.products;
var currentCartItem = allCartItems.Where(p => p.Product.ProductId.Equals(sessionId)).Select(p=>p).ToList();
List<Product> products = new List<Product>();
foreach (var item in currentCartItem)
{
var id = item.Product.ProductId;
if (id is null) { return View("NotFound"); }
Product prod = allProducts.Where(p => p.ProductId.Equals(id)).Select(p=>p).Single();
products.Add(prod);
}
return View(products);
}

ASP.NET MVC Dynamic Model not being recognized

I am trying to use 2 models in 1 view in an ASP.NET MVC application and am trying to use the dynamic model approach as described here: https://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/
This is my controller:
Details controller
// GET: Statewides/Details/5
public ActionResult Details(int? id)
{
ViewBag.ID = id;
var today = DateTime.Today;
var todayAsString = today.ToString("MM/dd/yyyy");
ViewBag.Today = todayAsString;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Statewide statewide = db.Statewides.Find(id);
var document = from s in db.Documents
where s.Statewide_ID == id
select s;
dynamic mymodel = new ExpandoObject();
mymodel.Statewides = statewide;
mymodel.Documents = document;
if (statewide == null)
{
return HttpNotFound();
}
return View(mymodel);
}
And this is a part of my view:
#model dynamic
#{
ViewBag.Title = "Details";
}
<div class="row">
<div class="col-md-9 text-left">
<h5><strong>COUNTY:</strong> <span class="box-shadow px-3">#Model.Statewide.COUNTY</span></h5>
</div>
<div class="col-md-3 text-right district">
<h5><strong>District:</strong>#Model.Statewide.District</h5>
</div>
</div>
And at the bottom of that page I need to access the Documents model:
<table>
<tr>
<th>Doc Type</th>
<th>Order Date</th>
<th>Location</th>
</tr>
#foreach (Document document in Model.Documents)
{
<tr>
<td>#document.Doc_Type</td>
<td>#document.Order_Date</td>
<td>#document.Doc_Location</td>
</tr>
}
</table>
Here I get an error on Document saying "The type or namespace Document could not be found". I'm not exactly sure what I'm doing wrong as it looks to me like I've done the same thing as the guide.
Here is the full view if you need it, PLEASE NOTE I have not changed a lot of the instances of the retrieving values from the old model that was only Statewide. Please ignore those:
#model dynamic
<!-- CUSTOM CSS -->
<link href="~/Styles/Documents/DetailsStyle.css" type="text/css" rel="stylesheet">
<!-- GOOGLE ICONS -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
#{
ViewBag.Title = "Details";
}
<div class="bigContainer">
<div class="container-fluid text-center topLabel">
<div class="borderline">
<h4 class="title"><strong>DETAIL RECORD - RP ROADWAY HISTORY FILE</strong></h4>
<div class="row">
<div class="col-md-1 printButton">
<input class="text-left" type="button" onclick="javascript:window.print()" value="Print" runat="server" />
</div>
<div class="col-md-11">
<p class="text-right">
<u>Current Date:</u>
<script>document.write(new Date().toLocaleDateString());</script>
</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-9 text-left">
<h5><strong>COUNTY:</strong> <span class="box-shadow px-3">#Model.Statewide.COUNTY</span></h5>
</div>
<div class="col-md-3 text-right district">
<h5><strong>District:</strong>#Model.Statewide.District</h5>
</div>
</div>
<div class="row">
<div class="col-md-4 text-left">
<h5><strong>Route No:</strong><span class="box-shadow px-4">#Html.DisplayFor(model => model.RouteNo)</span></h5>
</div>
<div class="col-md-4">
<h5><strong>Sign System:</strong><span class="box-shadow px-4 sign">#Html.DisplayFor(model => model.SignSys)</span></h5>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-12 text-left">
<h5><strong>LocalName:</strong></h5>
</div>
</div>
<div class="row">
<div class="col-md-4 text-left">
<h5 class="box-shadow px-3 localName">#Html.DisplayFor(model => model.LocalName)</h5>
</div>
<div class="col-md-8"></div>
</div>
<div class="row suppMethodDuplicate">
<div class="col-md-2 text-right">
<h5><strong>Supp Des:</strong></h5>
</div>
<div class="col-md-2 text-left">
<h5>#Html.DisplayFor(model => model.SuppDes)</h5>
</div>
<div class="col-md-2 text-right">
<h5><strong>Method:</strong></h5>
</div>
<div class="col-md-2 text-left">
<h5>#Html.DisplayFor(model => model.Method)</h5>
</div>
<div class="col-md-1"></div>
<div class="col-md-2 text-left">
#Html.DisplayFor(model => model.Duplicate_OK)
<label class="form-check-label" for="duplicateCheck"><strong>Duplicate OK</strong></label>
</div>
</div>
<div class="row">
<div class="col-md-2 text-right">
<h5><strong>Date:</strong></h5>
</div>
<div class="col-md-2 text-left">
<h5>#Html.DisplayFor(model => model.ReservedDate)</h5>
</div>
<div class="col-md-2 text-right">
<h5><strong>Original Location:</strong></h5>
</div>
<div class="col-md-2 text-left">
<h5>#Html.DisplayFor(model => model.OriginalL)</h5>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-2 text-right">
<h5><strong>Original D:</strong></h5>
</div>
<div class="col-md-6 text-left">
<h6>#Html.DisplayFor(model => model.OriginalD)</h6>
</div>
</div>
<div class="borderline text-left">
<h5 class="mb-0"><strong>DOCUMENTS</strong></h5>
</div>
<table>
<tr>
<th>Doc Type</th>
<th>Order Date</th>
<th>Location</th>
</tr>
#foreach (Document document in Model.Documents)
{
<tr>
<td>#document.Doc_Type</td>
<td>#document.Order_Date</td>
<td>#document.Doc_Location</td>
</tr>
}
</table>
<div class="borderline text-left">
<h5 class="mb-0"><strong>PROJECTS</strong></h5>
</div>
<h6 class="text-left">#Html.DisplayFor(model => model.Projects)</h6>
<div class="borderline text-left">
<h5 class="mb-0"><strong>COMMENTS</strong></h5>
</div>
<h6 class="text-left">#Html.DisplayFor(model => model.Comments)</h6>
</div>
<p style="margin-top: 20px">
#Html.ActionLink("Back to List", "Index")
</p>
</div>
Serge suggested I use view model so I have tried this:
ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Roadway_History.Models
{
public class ViewModel
{
public Statewide Statwide { get; set; }
public Document Document { get; set; }
}
}
Action
// GET: Statewides/Details/5
public ActionResult Details(int? id)
{
ViewBag.ID = id;
var today = DateTime.Today;
var todayAsString = today.ToString("MM/dd/yyyy");
ViewBag.Today = todayAsString;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var model = new ViewModel
{
Statewide statewide = db.Statewides.Find(id);
var document = from s in db.Documents
where s.Statewide_ID == id
select s;
};
if (statewide == null)
{
return HttpNotFound();
}
return View(model);
}
But this also doesn't work. I get the errors
Statewide is a type which is not valid in the given contextand ViewModel does not contain a definition for statewide
I belive the action method to be wrong but I'm not sure how to fix it.
Also, using #model ViewModel in the view gives the error "The type or namespace ViewModel could not be found"
if you need to use two models for one view you can make a viewmodel that contains both of them
public class ViewModel
{
public Statewide Statwide {get; set;}
public List<Document> Documents {get; set;}
}
in the view
#model ViewModel
action
var model = new ViewModel
{
Statewide= ... your code
Document=... your code
};
......
return View(model);
UPDATE
fix your viewmodel like this
var statewide = db.Statewides.FirstOrDefault (i=> i.Id==id);
if (statewide == null)
{
return HttpNotFound();
}
var documents = db.Documents.Where(s=> s.Statewide_ID == id).ToList();
if (documents == null)
{
return HttpNotFound();
}
var model = new ViewModel
{
Statewide =statewide,
Documents = documents
};
return View(model);
but you will need to fix model too according to new viewmodel

Error Post Method with Partial View

I have the following error when trying to post a partial view form on my page:
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
The error is related to the line below within the main view
The Main View is:
#{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
#Html.ActionLink("Create a Club", "SelectClubType", "Club")
</div>
<div>
#Html.Action("SelectClubType", "Club")
</div>
<div class="row">
<p>something here</p>
</div>
The Partial View is:
#model GRCWebApp.ViewModels.SelectClubTypeViewModel
#{
Layout = null;
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
<div class="row col-md-12">
<h3>Create a new Club - Select the type</h3>
</div>
<div class="row col-md-12">
<div class="col-md-3">
#Html.DropDownListFor(model => model.SelectedClubTypeId, new SelectList(Model.ClubTypes, "ClubTypeId", "ClubTypeName"), new { #class = "form-control" })
</div>
<div class="col-md-2 ">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
The Post Method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SelectClubType(SelectClubTypeViewModel model)
{
int id = model.SelectedClubTypeId;
return RedirectToAction("Create", new { id = id });
}

How to use 2 buttons on the same asp.net mvc form

In my asp.net mvc form I have 2 buttons, one to save which will save data from the from in a list in sharepoint and the second button does the same and additionally it applies some css colors.
I doubt however how to use 2 actions on the same form (same controller)
this is my view
#{
Layout = "~/Views/Shared/_LayoutPage2.cshtml";
}
#using (Html.BeginForm("Index", "Movies", FormMethod.Post))
{
<div class="row">
<div class="col-md-8">
<div class="col-xs-6 col-sm-3" id="stylesheet">Hojas de estilos</div>
<div class="col-xs-6 col-sm-3">
#Html.DropDownList("cssFiles", (IEnumerable<SelectListItem>)ViewBag.cssFiles, "Crear Nuevo", new { #class = "form-control", #id = "selCssFile" })
<span>
<input type="text" class="form-control" id="txtFileName" style="display:none;" placeholder="Nombre del archivo">
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Color base, links, botones, borde encabezado y pie
</div>
<div class="col-md-4">
<div id="colorSelector" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Fondo de la pagina, fondo de los cuadros
</div>
<div class="col-md-4">
<div id="colorSelector2" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Navegación
</div>
<div class="col-md-4">
<div id="colorSelector3" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Navegación (Item seleccionado)
</div>
<div class="col-md-4">
<div id="colorSelector4" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Pie de página
</div>
<div class="col-md-4">
<div id="colorSelector5" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row" id="buttons">
<div class="col-md-8">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-success">Guardar</button>
<button type="button" class="btn btn-primary">Guardar y aplicar</button>
</div>
</div>
}
My index action on the customize controller so far
public class CustomizeController : Controller
{
// GET: Customize
public ActionResult Index()
{
User spUser = null;
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var cc = spContext.CreateUserClientContextForSPHost())
{
int aprovisionado = (int)cc.Web.GetPropertyBagValueInt("Vinculosc.PlantillasIntranet.Aprovisionado", 0);
if (aprovisionado == 0)
{
string libraryName = "ConfiguraciónColores";
Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("Color1", "Text");
fields.Add("Color2", "Text");
fields.Add("Color3", "Text");
fields.Add("Color4", "Text");
fields.Add("Color5", "Text");
//ProvisionTemplate(cc);
CreateLibrary(cc, libraryName);
AddFields(cc, libraryName, fields);
}
}
#region comments
/*Uri hostWeb = new Uri(Request.QueryString["SPHostURL"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
var web = clientContext.Web;
clientContext.Load(web, w => w.Lists.Include(l => l.Title).Where(l => !l.hidden));
clientContext.ExecuteQuery();
return View(web.Lists);
}*/
#endregion
return View();
}
You can put the same name in the view with different value
<button type="submit" name="Guardar" value="guardar" class="btn btn-success">Guardar</button>
<button type="submit" name="Guardar" value="aplicar" class="btn btn-primary">Guardar y aplicar</button>
And in the Controller you can check the value of the button
if (Request["Guardar"].ToString() == "guardar")
{
//Your code for the first button
}
else
{
//Your code for the second button
}
Your button type should be "submit", and you can give them a name... Same name, that can be reused in a model, or by Request.Form["GiveAName"]
Your controller should have a
[HttpPost]
public ActionResult Index()
{
... Your code to retrieve form values
}
Anyway that's bad coding... You should work with models to inject on the view, that same model could be retrieved back and so you don't have to worry about retrieving form values. :=)

View is sending a null list of objects

I'm having a problem with a null list of objects when I try send from view to controller,
the jobOffertModel parameter is null
Here is my controller method: (I know it doesn't nothing, but I was testing the parameters)
[HttpPost]
public ActionResult AcceptJobOfferts(IEnumerable<JobOffertModel> jobOffertModel)
{
initBusinessObjects();
return View();
}
And Here is my View:
#model IEnumerable<TCCApplication.Models.JobOffertModel>
#{
ViewBag.Title = "Minhas ofertas de trabalho";
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm("AcceptJobOfferts","Professional")){
<div class="row">
<div class="col-md-9">
#foreach (var item in Model)
{
<div class="row">
<div class="col-md-2">
<label>Oferta: </label>
#Html.DisplayFor(itemModel => item.Description)
</div>
#if (item.Acepted)
{
<div class="col-md-2">
<label>Aceitar?</label>
#Html.DisplayFor(itemModel => item.Acepted)
</div>
}
else
{
<div class="col-md-2">
<label>Aceitar?</label>
#Html.EditorFor(itemModel => item.Acepted)
</div>
}
<div class="col-md-2">
<label>Ativa</label>
#Html.DisplayFor(itemModel => item.Active)
</div>
<div class="col-md-3">
<label>Data do trabalho</label>
#Html.DisplayFor(itemModel => item.JobDate)
</div>
</div>
}
</div>
<div class="col-md-2">
<input type="submit" value="Aceitar ofertas de trabalho"/>
</div>
</div>
}
The user goes to view using this method:
public ActionResult ViewMyJobOfferts(int professionalId)
{
initBusinessObjects();
var professionalJobOfferts = jobOffertBusiness.GetJobOffertsByProfessional(professionalId);
return View(professionalJobOfferts);
}
Changes what I have done -
Convert IEnumerable to List() with variable called modelList.
Used For Loop to display all property values.
Used hidden fields to persist only display element properties for POST operation.
Changed parameter name of POST Controller Action to modelList.
You got to have your view something like this -
#model IEnumerable<TCCApplication.Models.JobOffertModel>
#{
ViewBag.Title = "Minhas ofertas de trabalho";
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm("AcceptJobOfferts","Professional", FormMethod.Post)){
var modelList = Model.ToList();
<div class="row">
<div class="col-md-9">
for (int i = 0; i < modelList.Count; i++)
{
<div class="row">
<div class="col-md-2">
<label>Oferta: </label>
#Html.DisplayFor(itemModel => modelList[i].Description)
#Html.HiddenFor(itemModel => modelList[i].Description)
</div>
#if (modelList[i].Acepted)
{
<div class="col-md-2">
<label>Aceitar?</label>
#Html.DisplayFor(itemModel => modelList[i].Acepted)
#Html.HiddenFor(itemModel => modelList[i].Acepted)
</div>
}
else
{
<div class="col-md-2">
<label>Aceitar?</label>
#Html.EditorFor(itemModel => modelList[i].Acepted)
</div>
}
<div class="col-md-2">
<label>Ativa</label>
#Html.DisplayFor(itemModel => modelList[i].Active)
#Html.HiddenFor(itemModel => modelList[i].Active)
</div>
<div class="col-md-3">
<label>Data do trabalho</label>
#Html.DisplayFor(itemModel => modelList[i].JobDate)
#Html.HiddenFor(itemModel => modelList[i].JobDate)
</div>
</div>
}
</div>
<div class="col-md-2">
<input type="submit" value="Aceitar ofertas de trabalho"/>
</div>
</div>
}
And then your controller should be -
[HttpPost]
public ActionResult AcceptJobOfferts(IEnumerable<JobOffertModel> modelList)
{
initBusinessObjects();
return View();
}
Replace this line :
#using (Html.BeginForm("AcceptJobOfferts","Professional")){
By:
#using (Html.BeginForm("AcceptJobOfferts","Professional", FormMethod.Post)){

Categories

Resources