I want in Home/Index Load Partial View I Write This Code:
NewsPagingViewModel class:
public class NewsPagingViewModel
{
public IList<DommainCalsses.Models.News> News { get; set; }
public int CurrentPage { get; set; }
public int Count { get; set; }
public int Term { get; set; }
public int Page { get; set; }
public int TotalRecords { get; set; }
}
In Controller
public virtual ActionResult ShowNews(int page=0)
{
return PartialView(Views._News, new Posc.Model.News.NewsPagingViewModel() { CurrentPage = page, Count = 3, News = _newsService.GetList(page, 3), Term = 0, Page = page, TotalRecords = _newsService.GetCount() });
}
In _News partialView
#model Posc.Model.News.NewsPagingViewModel
#{
int currentPage = Model.CurrentPage + 1;
int count = Model.Count;
int max = (Model.TotalRecords % count == 0) ? Model.TotalRecords / count : (Model.TotalRecords / count) + 1;
const int size = 8;
int firstPage = ((currentPage - size) <= 0) ? 0 : currentPage - size;
int lastPage = ((currentPage + size) >= max) ? max : currentPage + size;
}
<div id="label-table">
#foreach (var item in Model.News)
{
<div class="row">
<div class="col-sm-1" style="padding-left: 5px;margin-left: 5px;">
<img src="#item.Image" />
</div>
<div class="col-sm-5">
#Html.ActionLink(item.Abstract, MVC.Admin.News.Index())
</div>
</div>
}
#* Page Navigation *#
<div class="pagination pagination-centered">
<ul>
#if (currentPage - 1 == firstPage)
{
<li class="active"><a>First</a></li>
}
else
{
<li>
#Ajax.ActionLink("First", MVC.Admin.News.ActionNames.ShowNews, MVC.Admin.News.Name, new { page = 0, count = Model.Count }, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, OnBegin = "showLoading", UpdateTargetId = "label-table", OnSuccess = "loadAjaxComponents", OnComplete = "hideLoading" }, null)
</li>
}
#for (int i = firstPage; i < lastPage; i++)
{
#*if (i + 1 == currentPage)
{
<li class="active"><a>#i+1</a></li>
#*Html.ConvertToPersianString(i + 1)
}
else
{*#
<li>
#*Html.ConvertToPersianString(i + 1).ToString()*#
#Ajax.ActionLink((#i + 1).ToString(), MVC.Admin.News.ActionNames.ShowNews, MVC.Admin.News.Name, new { page = #i }, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, OnBegin = "showLoading", UpdateTargetId = "News", OnSuccess = "loadAjaxComponents", OnComplete = "hideLoading" }, null)
</li>
#*}*#
}
#if (currentPage == lastPage)
{
<li class="active"><a>Last</a></li>
}
else
{
<li>
#Ajax.ActionLink("Last", MVC.Admin.News.ActionNames.ShowNews, MVC.Admin.News.Name, new { page = 0, count = Model.Count }, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, OnBegin = "showLoading", UpdateTargetId = "News", OnSuccess = "loadAjaxComponents", OnComplete = "hideLoading" }, null)
</li>
}
</ul>
</div>
</div>
And In Home/Index
<div id="News">
#Html.Action(MVC.Admin.News.ShowNews())
</div>
In the First Run Good Like This:
but when click in pagging Redirect to partial view Like this:
But I Want Refresh Partial View In Home/Index.
I would suggest you use the PagedList library. Its so awesome that Microsoft decided to use the library in their official tutorials (full tutorial here)
It provides a very clean code while doing pagination. See sample codes below.
Step 1
Add the PagedList.Mvc library using Nuget. https://www.nuget.org/packages/PagedList.Mvc/
Step 2
Integrate PagedList in your action method. Here is an example on how you could do it.
using PagedList;
public ActionResult ShowNews(int? page)
{
int currentPage = (page ?? 1);
// Fix negative page
currentPage = currentPage < 0 ? 1 : currentPage;
int pageSize = 3;
IEnumerable<Models.News> newsModels = newsService.GetList(currentPage, pageSize);
return View(newsModels.ToPagedList(currentPage, pageSize));
}
Step 3
Integrate PagedList in your View
#model PagedList.IPagedList<Models.News>
#using PagedList.Mvc;
#foreach (var item in Model.News)
{
<div class="row">
<div class="col-sm-1" style="padding-left: 5px;margin-left: 5px;">
<img src="#item.Image" />
</div>
<div class="col-sm-5">
#Html.ActionLink(item.Abstract, MVC.Admin.News.Index())
</div>
</div>
}
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action(MVC.Admin.News.ActionNames.ShowNews))
See complete tutorial here http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
Related
I am dynamically building a list based on data that is coming from my database
I am trying to make every list item clickable such that when one list item is clicked I can redirect to my controller "requistion" and enter the action in that controller "Details"
The list builds and displays successfully the only issue is that the list item itself is not clickable so I am not able to redirect to my controller and proceed with the rest of the logic
here is my code below)Please not that the code below is inside the _Layout.cshtml page
<div id="notifications">
<h3 class="notify"><b>Notifications</b></h3>
<div style="height:300px;">
<ul id="notiContent">
#if (ViewData["MessageList"] != null)
{
var viewDataProd = ViewData["MessageList"] as List<Notification>;
#for (var i = 0; i < viewDataProd.Count; i++)
{
#*<li class="notiContentLi"> <a asp-controller="Requisition" asp-action="Details" asp-route-id="#viewDataProd[i].RequisitionId"></a> #viewDataProd[i].Action</li>*#
#*<li class="notiContentLi"> <a asp-controller="Requisition" asp-action="Details" asp-route-id="#viewDataProd[i].RequisitionId"></a> #viewDataProd[i].Action</li>*#
<li class="notiContentLi"><a href='#Url.ActionLink("Details","Requisition",new{#viewDataProd[i].RequisitionId})'>click me </a>#viewDataProd[i].Action</li>
}
}
#if (GlobalVariables.messageList != null)
{
var viewDataProd = GlobalVariables.messageList as List<Notification>;
#for (var i = 0; i < viewDataProd.Count; i++)
{
#*<li class="notiContentLi">#c.Action<br /> </li>*#
#*<li class="notiContentLi" asp action>#viewDataProd[i].Action</li>*#
<li class="notiContentLi"><a href='#Url.ActionLink("Details","Requisition",new{#viewDataProd[i].RequisitionId})'> click me </a>#viewDataProd[i].Action</li>
}
}
</ul>
</div>
<div class="seeAll">See All</div>
</div>
You can add the onclick event to the <li> tag:
#for (var i = 0; i < viewDataProd.Count; i++)
{
<li class="notiContentLi" onclick="location.href = '#(Url.Action("Details", "Requistion", new { id = viewDataProd[i].RequisitionId }))'" >#viewDataProd[i].Action</li>
}
And the Details action method declaration in the Requistion controller is:
public ActionResult Details(int id)
{
// Add your action code here...
}
Adding route values and html attributes does the trick
var viewDataProd = GlobalVariables.messageList as List<Notification>;
#for (var i = 0; i < viewDataProd.Count; i++)
{
<li class="notiContentLi">#Html.ActionLink(#viewDataProd[i].Action, "Details", "Requisition", routeValues: new { #viewDataProd[i].RequisitionId }, htmlAttributes: new { target = "_blank" })</li>
}
Index.cshtml
...
<div class="card-columns">
#foreach (var yourElement in Model.YourElements)
{
<div class="card">
<div class="card-body"
onclick="location.href =
'/AnotherElementsPage/ByID/?ID=#yourElement.AnotherElement.ID'" >
<h6 class="card-title">#yourElement.Name</h6>
<h7 class="card-text">#yourElement.Description</h7>
</div>
</div>
}
</div>
AnotherElementsPage.cshtml
#page "{handler?}"
AnotherElementsPage.cshtml.cs
public AnotherElementsService AnotherElementsService;
[BindProperty(SupportsGet = true)]
public IEnumerable<AnotherElement> AnotherElements { get; private set; }
public void OnGet()
{
AnotherElements = AnotherElementsService.GetAnotherElements().ToList();
}
public void OnGetByID(Guid ID)
{
AnotherElements = AnotherElementsService.GetAnotherElement(ID).ToList();
}
my partial view work quickly and well when run it local but when Publish it on server my partial view work very slowly and website is heavy
my partial code is
<script type="text/javascript">
function Son(id)
{
this.id_ = id;
var d = 'div#' + id_;
var urId = '#Url.Action("Son","Tree")';
$(d).load(urId , {id:id_}).ajaxSuccess();
//Son2(id);
}
</script>
<script type="text/javascript">
function Son2(id)
{
this.id_ = id;
var urId2 = '#Url.Action("DivSon","Tree")';
$('div.inn_height').load(urId2 , {id:id_}).ajaxSuccess();
}
</script>
#{ var father = Model.Where(a => a.Parent_Id == 0).FirstOrDefault();
var main = Model.Where(a => a.Parent_Id == father.id).ToList();}
<ul class="list_family">
#if (main.Count() > 0)
{
for (int i = 0; i < main.Count(); i++)
{
var item = main.ElementAt(i);
<li id="#item.id">
<div>
<div class="manu">
#if (item.Wife_Image != null)
{
<div class="wife"><img class="img_wife" src="#Url.Content(item.Wife_Image)"></div>
}
#if (item.Wife_Image == null && item.IsMarried=="forsale")
{
<div class="wife"><img class="img_wife" src="~/Content/img/visa.png" style="visibility:hidden"></div>
}
<a onclick="Son('#item.id');Son2('#item.id');">
<img src="#Url.Content(item.Image)">
</a>
</div>
<i><strong>#item.Name</strong></i>
</div>
</li>
}
}
</ul>
c#
family2016Entities db = new family2016Entities();
[OutputCache(Duration = 10, Location = System.Web.UI.OutputCacheLocation.ServerAndClient)]
public ActionResult Index()
{
return View(db.Trees.OrderByDescending(a => a.id));
}
[OutputCache(Duration = 10, Location = System.Web.UI.OutputCacheLocation.ServerAndClient)]
public ActionResult Son(int id)
{
ViewBag.Grand = id;
var child = db.SELECTTreeSonrecords(id).ToList();
return PartialView("Son", child);
}
[OutputCache(Duration = 10, Location = System.Web.UI.OutputCacheLocation.ServerAndClient)]
public ActionResult DivSon(int id)
{
ViewBag.Grand2 = id;
var details = db.SELECTTreerecords(id).FirstOrDefault();
return PartialView("DivSon", details);
}
what can i do to make my partial view work quickly when publish it
and What's the alternative for partial view to work well
so my intention is to make a button that allow a user to add an item to his Cart, in the db.savechanges method it catch these exceptions :
Property: Item_Name Error: The Item_Name field is required.
iisexpress.exe Information: 0 : Property: Item_Description Error:
The Item_Description field is required. s
i checked from my db and every single item has all their properties filled up, since i am new to asp.net i am surely missing something obvious that is messing with my data.
this is the view(trying to pass the item object in actionlink
#foreach (var item in Model)
{
if (index > 6)
{
index = 0;
}
var newrow = 0;
if (index == 0)
{
newrow = 1;
}
if (newrow == 1)
{
index++;
<div class="product-one">
<div class="col-md-2 product-left">
<div class="p-one simpleCart_shelfItem jwe">
<a href="single.html">
<!-- go to product single view page-->
#{ if (item.Image.Image1 != null)
{
string imageBase64 = Convert.ToBase64String(item.Image.Image1);
string imageSrc = string.Format("data:image/png;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}
}
#Html.ActionLink("Add to Cart", "AddToCart", "Carts", new { itemdata = item }, new { #class = "btn btn-primary btn-large" })
</a>
<br />
</div>
</div>
</div>
this is the controller:
public ActionResult AddToCart(Item item)
{
//var query = from itemsel in db.Items where item.Item_ID == item.Item_ID select item;
var newcart = new Cart();
newcart.Account_ID = 1;
newcart.Cart_ID = 3;
newcart.Item_ID = item.Item_ID;
newcart.Item = item;
var itemsgroup = db.Items;
try
{
db.Carts.Add(newcart);
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
return View(itemsgroup.ToList());
}
and this is the cart model:
public partial class Cart
{
public int Cart_ID { get; set; }
public int Account_ID { get; set; }
public int Item_ID { get; set; }
public virtual Item Item { get; set; }
}
}
p.s i know my view is tricky but i am desperate to finish this project very soon, any suggestion for a better way of doing it would be welcomed
Since you are missing too many pieces, I could only point you to right direction.
Download the sample source code of Pro ASP.NET MVC 5 book By Adam Freeman.
Extract Chapter 9 - SportsStore, and look at those two files-
SportsStore.WebUI > Views > Product > List.cshtml
#foreach (var p in Model.Products) {
#Html.Partial("ProductSummary", p)
}
SportsStore.WebUI > Views > Shared > ProductSummary.cshtml
Notice that it uses BeginForm to add individual item to shopping cart.
#using (Html.BeginForm("AddToCart", "Cart")) {
<div class="pull-right">
#Html.HiddenFor(x => x.ProductID)
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-success" value="Add to cart" />
</div>
}
I have used from dropdownlist in page.
I want, when change selected id info, load bottom of page.
first time that page load is true,but with dropdown change load info in new page, not part of current page.
Fill dropdown list
public ActionResult selVahedList(int IdType, int IdChoose)
{
ViewBag.ChooseItem = IdChoose;
IEnumerable<Lcity> Lcitys = Dbcon.Lcitys;
var model = new CityViewMode
{
Lcitys = Lcitys.Select(x => new SelectListItem
{
Value = x.Citycode.ToString(),
Text = x.CityName
})
};
return View(model);
});
Partial view shows after dropdown changed
public ActionResult selVahedListAjax(CityViewMode model)
{
int idcity=Convert.ToInt32(model.SelectedCitycode);
// int idcity = 1;
ViewBag.Reshteh = 1;
//string IdCity = base.Request["SelValue"].ToString();
var res = Dbcon.TaavoniInfos.Where(m => m.IDReshteh == 1 && m.Citycode ==idcity);
return PartialView("selVahedListAjax", res);
}
view page
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "LoadData",
LoadingElementId="loadAdmin"
};
#using (Ajax.BeginForm("selVahedListAjax",ajaxOpts))
{
<fieldset>
<div class="PContent">
<p class="DroplistCity" id="DroplistCity">
#Html.DropDownListFor(
x => x.SelectedCitycode,
new SelectList(Model.Lcitys, "Value", "Text",""))
<div id="LoadData">
#Html.Action("selVahedListAjax", new { IdReshte = ViewBag.ChooseItem })
</div>
</div>
</fieldset>
}
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#SelectedCitycode').change(function () {
this.form.submit();
});
});
</script>
thanks for your help
my partial view code is: #model
IEnumerable<TaavonS.Models.TaavoniInfo>
<ul>
#foreach (var item in Model)
{
<li>:<b>#Html.DisplayFor(modelItem => item.SName)</b></li>
<li>:<b>#Html.DisplayFor(modelItem => item.ModirName)</b></li>
<li><img src="#Url.Content("~/Content/img/list16.png")" alt=""/>
#Html.ActionLink("detail....", "Detaild",new { codef= item.Scode }, new { #class = "openDialog", data_dialog_id = "emailDialog", data_dialog_title = "" } )
<hr class="separatorLine"/></li> when i load page is true but after dropdownlist is nt work
<li>
#if (!string.IsNullOrEmpty(item.TablighatPic))
{
<img src="#Url.Content("~/Content/img/eye.png")"/> #Html.ActionLink("تبلیغات....", "showImg", new { code = item.Scode }, new { #class = "openImg", data_dialog_id = "mailDialog" })<hr class="separatorLine"/>
}
</li>
}
</ul>
I think you need to change your ajaxOptions:
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "LoadData",
LoadingElementId="loadAdmin",
InsertionMode = InsertionMode.Replace // add this line
};
Add the parameter to the beginForm call
#using (Ajax.BeginForm("selVahedListAjax",
new { IdReshte = ViewBag.ChooseItem }, //add this to the Ajax.BeginForm call
ajaxOpts ))
{
and remove this line from the target div if you don't want the ajax call performed before the user chooses anything
#Html.Action("selVahedListAjax", new { IdReshte = ViewBag.ChooseItem })
I have problems in displaying page on how to include the prev and next link...
I am using ASP.Net MVC 4 using these codes:
VIEW:
<div class="pagination">
<ul>
#for (int i = 1; i <= ViewBag.PagesCount; i++)
{
<text>
<li>#Html.ActionLink(i.ToString(), "Index", new { pagee = i })</li>
</text>
}
</ul>
</div>
CONTROLLER:
int offset = 15;
int pagecount = ((pagee - 1) * offset);
int totalPages = 0;
int totalItems = 0;
try
{
totalItems = requestform.Count();
while (totalItems > 0)
{
totalItems -= 15;
totalPages++;
}
ViewBag.PagesCount = totalPages;
return View(requestform.Skip(pagecount).Take(offset).ToList());
}
catch
{
while (totalItems > 0)
{
totalItems -= 15;
totalPages++;
}
ViewBag.PagesCount = totalPages;
return View(requestform.Skip(pagecount).Take(offset).ToList());
}
Please help me with this.
What do you say about this little extension PagedList ?
To add paging to page, you'll start by installing the PagedList NuGet package. Then you'll make additional changes in the Index method and add paging links to the Index view
Please check this link
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
I would recommend also PagedList just add it via NuGet package manager and then,
modify your controller to look like this:
public ActionResult Index(int? page)
{
var dbtable = db.DbTable.Include(s => s.ID).OrderBy(s => s.StyleName); //ensure records are sorted.
if (Request.HttpMethod != "GET")
{
page = 1;
}
int pageSize = 2;
int pageNumber = (page ?? 1);
return View(dbtable.ToPagedList(pageNumber, pageSize));
}
in view replace:
#model IEnumerable<MyMvcApplication.Models.dbtable>
with
#model PagedList.IPagedList<MyMvcApplication.Models.dbtable>
replace code that looks like
<th>
#Html.DisplayNameFor(model => model.ID)
</th>
with
<th>
#Html.DisplayNameFor(model => model.First().ID)
</th>
at the end of the page after the </table> tag add this:
<div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<", "Index", new { page = 1})
#Html.Raw(" ");
#Html.ActionLink("< Prev", "Index", new {page = Model.PageNumber - 1})
}
else{
#:<<
#Html.Raw(" ");
#:< Prev
}
#if (Model.HasNextPage)
{
#Html.ActionLink("Next >", "Index", new {page = Model.PageNumber + 1})
#Html.Raw(" ");
#Html.ActionLink(">>", "Index", new {page = Model.PageCount})
}
else{
#:Next >
#Html.Raw(" ")
#:>>
}
</div>
recently i found with cool controls, tooltip, first, next, last, previous check this mvc 4 paging nuget package, demo web page