Paging in webgrid not working in asp.net mvc 5 - c#

I have following view and controller. Problem is that when enabling paging and I click on next page, previous view is gone
#using System
#using System.Web.Helpers
#*#model List<DataTransferObjects.UserClaimHistory>*#
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="~/Content/style.css" rel="stylesheet" type="text/css" />
#*<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>*#
<script src="~/Scripts/jquery-1.7.1.js"></script>
<style>
/*Here I will write some css for looks good*/
th, td {
padding: 5px;
}
th {
background-color: gray;
}
</style>
</head>
#{
ViewBag.Title = "ViewReports";
var grid = new WebGrid(Model, canPage: false, rowsPerPage: 2, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent", canSort: false);
}
#{
var fromDateVal = (DateTime)ViewBag.fromDate;
var toDateVal = (DateTime)ViewBag.toDate;
}
#using (Html.BeginForm("Index", "ViewReport", FormMethod.Post))
{
<div class="container">
#{
var homeHeader = Html.Partial("_HomeHeader");
}
#homeHeader
<div id="logout-div">
#Html.ActionLink("Log Out", "Logout", "Home", null, null )
</div>
#{
var homeLeftPanel = Html.Partial("_HomeLeftPanel");
}
#homeLeftPanel
<div>
From Date: #Html.TextBox("fromDate", string.Format("{0:yyyy-MM-dd}", fromDateVal), new { #id = "fromDate", #class = "datefield", type = "date" })
To Date: #Html.TextBox("toDate", string.Format("{0:yyyy-MM-dd}", toDateVal), new { #id = "toDate", #class = "datefield", type = "date" })
<input type="submit" value="Search" />
</div>
<div id="main" style="padding: 25px;">
#grid.GetHtml(
htmlAttributes: new { id = "MainGrid", width = "60%" },
tableStyle: "table table-bordered table-responsive",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("UserName", "User Name"),
grid.Column("Email", "Email"),
grid.Column("Claim", "Accessed"),
grid.Column(header: "AccessedOn", format: (item) => string.Format("{0:dd-MM-yyyy}", item.AccessedOn)),
grid.Column(format: (item) =>
{
if (item.Count > 1)
{
var subGrid = new WebGrid(source: item.List, canSort: false);
return subGrid.GetHtml(displayHeader: true,
htmlAttributes: new { id = "SubGrid", width = "100%" },
columns: subGrid.Columns(
subGrid.Column("UserName", "User Name"),
subGrid.Column("Email", "Email"),
subGrid.Column("Claim", "Accessed"),
subGrid.Column("AccessedOn", "AccessedOn")
)
);
}
else
{
return null;
}
})
)
)
<script>
$(document).ready(function () {
var size = $("#main #MainGrid > thead > tr > th").size(); // get total column
$("#main #MainGrid > thead > tr > th").last().remove(); // remove last column
$("#main #MainGrid > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
$("#main #MainGrid > tbody > tr").each(function (i, el) {
$(this).prepend(
$("<td></td>")
.addClass("expand")
.addClass("hoverEff")
.attr('title', "click for show/hide")
);
//Now get sub table from last column and add this to the next new added row
var table = $("table", this).parent().html();
//
// alert(table);
//add new row with this subtable
// ADD CLICK EVENT FOR MAKE COLLAPSIBLE
if (table !== null) {
$(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
$("table", this).parent().remove();
$(".hoverEff", this).live("click", function () {
$(this).parent().closest("tr").next().slideToggle(100);
$(this).toggleClass("expand collapse");
});
} else {
$(this).find('td:eq(0)').removeClass();
}
});
//by default make all subgrid in collapse mode
$("#main #MainGrid > tbody > tr td.expand").each(function (i, el) {
$(this).toggleClass("expand collapse");
$(this).parent().closest("tr").next().slideToggle(100);
});
});
</script>
</div>
#if (ViewBag.Count > 0)
{
<div>
#Html.ActionLink("Export", "ExportToExcel", "ViewReport", new { fromDate = fromDateVal, toDate = toDateVal}, null)
</div>
}
#{
var homeFooter = Html.Partial("_HomeFooter");
}
#homeFooter
</div>
}
</html>
And this is the controller:
public ActionResult Index(DateTime? fromDate, DateTime? toDate)
{
if (!fromDate.HasValue)
fromDate = DateTime.Now.Date;
if (!toDate.HasValue)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
if (toDate < fromDate)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
ViewBag.fromDate = fromDate;
ViewBag.toDate = toDate;
var userClaims = DbAccessWebApiHandler.GetUserClaimAccesshistory(new DateSelection
{
StartDate = fromDate.Value,
EndDate = toDate.Value
});
if (userClaims != null)
{
ViewBag.Count = userClaims.Count;
var newList = userClaims.GroupBy(x => new { x.UserName, x.Email, x.Claim, x.AccessedOn.Date })
.Select(y => new UserClaimHistoryGroup
{
UserName = y.Key.UserName,
Email = y.Key.Email,
Claim = y.Key.Claim,
AccessedOn = y.Key.Date,
List = y.ToList(),
Count = y.ToList().Count
});
return View(newList);
}
userClaims = new List<UserClaimHistory>();
return View(userClaims);
}
[System.Web.Mvc.HttpGet]
public ActionResult ExportToExcel(DateTime? fromDate, DateTime? toDate)
{
if (!fromDate.HasValue)
fromDate = DateTime.Now.Date;
if (!toDate.HasValue)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
if (toDate < fromDate)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
ViewBag.fromDate = fromDate;
ViewBag.toDate = toDate;
var userClaims = DbAccessWebApiHandler.GetUserClaimAccesshistory(new DateSelection
{
StartDate = fromDate.Value,
EndDate = toDate.Value
});
if (userClaims != null)
{
var gv = new GridView();
gv.AutoGenerateColumns = false;
gv.Columns.Add(new BoundField { HeaderText = "UserName", DataField = "UserName" });
gv.Columns.Add(new BoundField { HeaderText = "Email", DataField = "Email" });
gv.Columns.Add(new BoundField { HeaderText = "Accessed", DataField = "Claim" });
gv.Columns.Add(new BoundField { HeaderText = "Date", DataField = "AccessedOn" });
var dt = new DataTable();
dt.Columns.Add("UserName");
dt.Columns.Add("Email");
dt.Columns.Add("Claim");
dt.Columns.Add("AccessedOn");
foreach (var item in userClaims)
{
dt.Rows.Add(item.UserName, item.Email, item.Claim, item.AccessedOn);
}
gv.DataSource = dt;
gv.DataBind();
for (var i = 0; i < userClaims.Count; i++)
{
gv.Rows[i].Height = 40;
}
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Reports.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
var sw = new StringWriter();
var htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
return View("Index");
}

Have able to work via following script
var links = $('a[href*=page], a[href*=sort]'), form = $('form');
links.click(function () {
form.attr("action", this.href);
$(this).attr("href","javascript:");
form.submit();
});
as mentioned in How do I get my WebGrid to POST instead of GET during a sort or paging operation in my MVC4 site?

Related

HighCharts chart asp.net mvc rendering

Hi I'm trying to use DotNet HighCharts to create a simple chart to display my ticket sales data in my C# asp.net MVC site.
I wish to create a bar/column chart which will show how many tickets in total were available for the event and how many are remaining. I had planned to pass the chart to the view and display it. However my chart is not rendered in my view and I cannot find a reason why it won't display, any help would be greatly appreciated!
This is my controller method
[Authorize(Roles = "canEdit")]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest)
}
Event events = db.Events.Find(id);
if (events == null)
{
return HttpNotFound();
}
Highcharts chart = new Highcharts("chart")
.SetCredits(new Credits { Enabled = false })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetTitle(new Title { Text = "Ticket Sales" })
.SetXAxis(new XAxis { Categories = new[] { "Total Tickets", "Tickets Remaining"} })
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle { Text = "Quantity" }
})
.SetTooltip(new Tooltip { Formatter = "function() { return ''+ this.series.name +': '+ this.y +''; }" })
.SetPlotOptions(new PlotOptions { Bar = new PlotOptionsBar { Stacking = Stackings.Normal } })
.SetSeries(new[]
{
new Series { Name = "Total", Data = new Data(new object[] { events.TicketsAvailable, events.TicketsRemaining }) }
});
return View(chart);
}
And this is my view
#model DotNet.Highcharts.Highcharts
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<head>
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
<title>Event Title</title>
</head>
<body>
<p>Chart Displaying Ticket Sales </p>
<div>#(Model)</div>
<div>
#Html.ActionLink("Back to List", "Index", "EventsAdmin")
</div>
</body>
I think the issue is that your js files are not loading.
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
I tried the following code and it worked for me. You can modify the code as per your requirements.
View:
#model DotNet.Highcharts.Highcharts
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.jquery.com/jquery-1.12.1.min.js" integrity="sha256-I1nTg78tSrZev3kjvfdM5A5Ak/blglGzlaZANLPDl3I=" crossorigin="anonymous"></script>
<head>
<title>Event Title</title>
</head>
<body>
<p>Chart Displaying Ticket Sales </p>
<div>#(Model)</div>
</body>
Controller:
public ActionResult Index()
{
object[] desktops = new object[] {17368, 17792, 18235, 18136 };
var monthsList = new[] { "Feb-15", "Mar-15", "Apr-15", "May-15",};
Highcharts chart = new Highcharts("chart")
.SetCredits(new Credits { Enabled = false })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column , Height = 190, Width=190})
.SetTitle(new Title { Text = "Ticket Sales" })
.SetXAxis(new XAxis { Categories = monthsList, Labels = new XAxisLabels() { } })
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle { Text = "Quantity" }
})
.SetTooltip(new Tooltip { Formatter = "function() { return ''+ this.series.name +': '+ this.y +''; }" })
.SetPlotOptions(new PlotOptions { Column = new PlotOptionsColumn{ Color = System.Drawing.Color.Black } })
.SetSeries(new[]
{
new Series { Name = "Total", Data = new Data(desktops) }
});
return View(chart);
}
If you still face issues, look into your browser's debug console if there are any javascript issues.

Sorting date using KnockoutJS

Firstly, I'd like to thank you for reading this post.
I have a small problem, I am trying to sort my posts in descending order of date created. It sorts the date in descending order by the posts created today and yesterday get mixed up.
For example: Posts created show as;
Created: Today, Created: Yesterday, Created: 29/09/2015, Created: 28/09/2015
After sorting they're displayed in this order:
Created: Yesterday,
Created: Today,
Created: 29/09/2015,
Created: 28/09/2015,
The code I am using is shown below
foreach.Posts.sort(function (l, r) { return l.Created() > r.Created() ? -1 : 1 })
Is there a way around this ?
Thank you.
Updated: Added C# Class
[HttpGet]
public LivePostModel GetPosts(string id, string page = null, string startDate = "", string endDate = "")
{
Thread thread = _threadManager.GetThreadByDomain(id);
if (thread == null)
return new LivePostModel();
DateTime? dtDateFrom = null;
DateTime? dtDateTo = null;
if (string.IsNullOrEmpty(startDate) == false)
dtDateFrom = DateTime.Parse(startDate);
if (string.IsNullOrEmpty(endDate) == false)
dtDateTo = DateTime.Parse(endDate);
PostWithCount posts = _postManager.GetPosts(new PostsFilter
{
SubDomain = id,
Page = string.IsNullOrEmpty(page) ? 0 : int.Parse(page),
StartDate = dtDateFrom,
EndDate = dtDateTo
});
IOrderedEnumerable<Post> sortedPosts = posts.Items.OrderByDescending(x => x.Created);
var postsModel = new List<PostModel>();
List<string> userKeys = sortedPosts
.Select(obj => obj.CreatedByUserId)
.Distinct()
.ToList();
IList<User> users = _userManager.GetUsersByKeys(userKeys);
foreach (Post post in sortedPosts)
{
User user = users.FirstOrDefault(u => u.Key == post.CreatedByUserId);
if (user != null)
{
PostModel postModel = Mapper.Map<Post, PostModel>(post);
postModel.User = GetUserDetails(postModel.User, user);
postsModel.Add(postModel);
}
}
var model = new LivePostModel
{
Posts = postsModel.ToList(),
CountPages = posts.Count.ToString(CultureInfo.InvariantCulture),
CountItems = posts.CountItems.ToString(CultureInfo.InvariantCulture),
CurrentId = thread.Key,
Subdomain = thread.Subdomain,
CurrentUserName = UserContextService.IsAuthenticated ? UserContextService.Key : String.Empty,
OwnerThreadName = thread.OwnerUserId,
OwnerThreadFullName = string.Format("{0} {1}", thread.FirstName, thread.LastName),
CanAddPost = _threadManager.IsCurrentUserCanUploadContent(thread)
};
model.CurrentUserCanDelete = CheckIfUserCanDeletePost(thread);
return model;
}
JSON Data:
"Posts":[
{"Key":"Post_ab780bb71",
"Header":null,
"Message":"Post details go here ",
"PostId":"Post_11338",
"Created":"today",
"Modified":"today",
"User":{ User Details below }
Yes, however you'll need to make some changes...
You need to use a sortable time format... For example, 2015-10-02T10:09:56.
I assume the posts have a property called CreatedOn which indicate whether it was posted today yesterday etc... Add another property called CreatedOnSortable that includes the actual DateTime in the format show, you can do this by calling ToString('s') on the DateTime...
DateTime.UtcNow.ToString("s");
Edit
HomeController
public ActionResult Index()
{
var livePostModel = new PostsViewModel
{
Posts = new Post[]
{
new Post
{
Created = "Today",
CreatedDateTime = DateTime.UtcNow,
Header = "Todays Post",
Key = Guid.NewGuid().ToString(),
Message = "Todays message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
new Post
{
Created = "Yesterday",
CreatedDateTime = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
Header = "Yesterdays Post",
Key = Guid.NewGuid().ToString(),
Message = "Yesterdays message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
new Post
{
Created = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)).ToString("D"),
CreatedDateTime = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)),
Header = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)).ToString("D") + " Post",
Key = Guid.NewGuid().ToString(),
Message = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)).ToString("D") + " message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
new Post
{
Created = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)).ToString("D"),
CreatedDateTime = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)),
Header = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)).ToString("D") + " Post",
Key = Guid.NewGuid().ToString(),
Message = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)).ToString("D") + " message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
}
};
this.ViewBag.Json = JsonConvert.SerializeObject(livePostModel);
return View();
}
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<div class="row" data-bind="foreach: posts">
<div class="col-md-6" data-bind="text: Created"></div>
<div class="col-md-6" data-bind="text: CreatedSortable"></div>
</div>
<div class="row">
<div class="col-md-6"><button data-bind="click: orderByAsc">Order Ascending</button></div>
<div class="col-md-6"><button data-bind="click: orderByDesc">Order Descending</button></div>
</div>
#section scripts{
<script src="~/Scripts/knockout-3.3.0.js" type="text/javascript"></script>
<script type="text/javascript">
var json = #this.Html.Raw(this.ViewBag.Json);
function Post(post) {
var self = this;
self.key = ko.observable(post.Key || '');
self.header = ko.observable(post.Header || '');
self.message = ko.observable(post.Message || '');
self.postId = ko.observable(post.PostId || '');
self.created = ko.observable(post.Created || '');
self.createdSortable = ko.observable(post.CreatedSortable || '');
self.modified = ko.observable(post.Modified || '');
}
function PostsViewModel(model)
{
var self = this;
self.posts = ko.observableArray(model.Posts);
self.orderByAsc = function() {
self.posts.sort(function(left, right) { return left.CreatedSortable == right.CreatedSortable ? 0 : (left.CreatedSortable < right.CreatedSortable ? 1:-1 ) });
}
self.orderByDesc = function() {
self.posts.sort(function(left, right) { return left.CreatedSortable == right.CreatedSortable ? 0 : (left.CreatedSortable < right.CreatedSortable ? -1: 1 ) });
}
}
ko.applyBindings(new PostsViewModel(json));
</script>
}
Result
Ascending
Descending

How to Bind Data in Webgrid usig PartialView in ASP.net MVC

Iam new to .Net MVC. I need to bind data into webgrid return using PartialView(),or
If it is possible to return back using JSON,Now My code will execute on Dropdown change,But it will not bind values in web grid.
JavaScript,Model,Controller Codes are shown below:
Script
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.post('#Url.Action("SelectCustomerByID", "Admin")', {secondValue:firstDDLValue }, function (ReceiptList) {
alert(firstDDLValue);
$('#divgrid').html(ReceiptLists);
});
});
});
</script>
View:
<div id="divgrid" style="margin-top: 15px;">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns: grid.Columns(
grid.Column("Id", "ID", style: "id"),
grid.Column("Cust_Name", "Cust Name", style: "PName"),
grid.Column("Pay_Amount", "Pay_Amount", style: "ICode"),
grid.Column("Pay_Mode", "Pay_Mode", style: "IName"),
grid.Column("Bank_Name", "Bank_Name", style: "Weight"),
grid.Column("Bank_Address", " Bank_Address", style: "MakingCharge"),
grid.Column("ChequeNo", "ChequeNo", style: "Certification"),
grid.Column("Cheque_Date", " Cheque_Date", style: "Price"),
grid.Column("Date", "Date", style: "Price"),
grid.Column("Edit", "", #<a href='../Admin/EditReceipt?id=#item.ID' ><img src="~/Images/edit.png" alt='Edit' /></a>, style: "width:10%"),
grid.Column(header: "Delete", format: #<text><img src="../Images/delete.png" alt='Delete' /></text>) ))
#if (grid.HasSelection)
{
Receipt = (JewellaryWeb.Models.Receipt)grid.Rows[grid.SelectedIndex].Value;
<b>Id</b> #Receipt.Id<br />
<b>Name</b> #Receipt.Cust_Name<br />
<b>Amount</b> #Receipt.Pay_Amount<br />
<b>PayMode</b> #Receipt.Pay_Mode<br />
<b>BankName</b> #Receipt.Bank_Name<br />
<b>BankAddress</b> #Receipt.Bank_Address<br />
<b>ChequeNumber</b> #Receipt.ChequeNo<br />
<b>ChequeDate</b> #Receipt.Cheque_Date<br />
}
</div>
Controller:
public ActionResult SelectCustomerByID(Receipt model,string secondValue)
{
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
model.ReceiptList = Receipt.GetReceiptListByCustID(CustID);
return PartialView(model.ReceiptList);
}
I found answer for this I just modified my Script and Use ParitalView to bind data in gird My Solution Code is:
Script
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.get('#Url.Action("SelectCustomerByID", "Admin")', { secondValue: firstDDLValue }, function (ReceiptList) {
$('#gridContent').html(ReceiptList);
});
});
});
</script>
i create new _Recepitgrid.cshtml as PartialView and write the code for Webgrid as Same as in the main view.
Controller
public ActionResult SelectCustomerByID(Receipt model, string secondValue)
{
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
ReceiptList = Receipt.GetReceiptListByCustID(CustID);
return PartialView("_Recepitgrid", ReceiptList);
}
Now it will works fine..

How to Bind JSON return result value in webgird on ASP.net MVC4

I want to bind Datatable values in webgrid using Json. I used DropDownlist to select Name of person dependent on those names i want to bind it in webgrid.Now i used some codes but unable t bind data in grid.
My Code Is:
View
<div id="divgrid" style="margin-top: 15px;">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns: grid.Columns(
grid.Column("Id", "ID", style: "id"),
grid.Column("Cust_Name", "Cust Name", style: "PName"),
grid.Column("Pay_Amount", "Pay_Amount", style: "ICode"),
grid.Column("Pay_Mode", "Pay_Mode", style: "IName"),
grid.Column("Bank_Name", "Bank_Name", style: "Weight"),
grid.Column("Bank_Address", " Bank_Address", style: "MakingCharge"),
grid.Column("ChequeNo", "ChequeNo", style: "Certification"),
grid.Column("Cheque_Date", " Cheque_Date", style: "Price"),
//grid.Column("Cheque_Date", "Cheque_Date", format: item => ((item.Cheque_Date == null) ? "" : item.Cheque_Date.ToString("dd/MM/yyyy")), style: "name"),
grid.Column("Date", "Date", style: "Price"),
grid.Column("Edit", "", #<a href='../Admin/EditReceipt?id=#item.ID' ><img src="~/Images/edit.png" alt='Edit' /></a>, style: "width:10%"),
grid.Column(header: "Delete", format: #<text><img src="../Images/delete.png" alt='Delete' /></text>)
))
#if (grid.HasSelection)
{
Receipt = (JewellaryWeb.Models.Receipt)grid.Rows[grid.SelectedIndex].Value;
<b>Id</b> #Receipt.Id<br />
<b>Name</b> #Receipt.Cust_Name<br />
<b>Amount</b> #Receipt.Pay_Amount<br />
<b>PayMode</b> #Receipt.Pay_Mode<br />
<b>BankName</b> #Receipt.Bank_Name<br />
<b>BankAddress</b> #Receipt.Bank_Address<br />
<b>ChequeNumber</b> #Receipt.ChequeNo<br />
<b>ChequeDate</b> #Receipt.Cheque_Date<br />
}
</div>
Script:
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
// alert(firstDDLValue);
$.post('#Url.Action("SelectCustomerByID", "Admin")', { secondValue: firstDDLValue }, function (ReceiptList) {
alert(firstDDLValue);
var grdPipeline = $find("#grid");
grdPipeline.set_dataSource(ReceiptList);
grdPipeline._pi.show(grdPipeline);
grdPipeline.applyClientBinding();
grdPipeline._pi.hide(grdPipeline);
alert(firstDDLValue);
$("#ItemName").text(Data);
});
});
});
</script>
Control:
public JsonResult SelectCustomerByID(string secondValue)
{
Receipt Recepit = new Receipt();
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
ReceiptList = Recepit.GetReceiptListByCustID(CustID);
return Json(ReceiptList, JsonRequestBehavior.AllowGet);
}
Model:
public ObservableCollection<Receipt> GetReceiptListByCustID(int CustID)
{
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
DataTable dtReceipt = new DataTable();
DbParameter[] objParams = new DbParameter[1];
objParams[0] = objDAL.CreateParameter("#REC_Cust_ID", DbType.Int32, CustID);
dtReceipt = objDAL.ExecuteTable(CommandType.StoredProcedure, "[sp_Receipt_Select_ByCustID]",objParams);
foreach (DataRow dr in dtReceipt.Rows)
{
ReceiptList.Add(new Receipt
{
Id = Convert.ToInt32(dr["REC_Id_I"]),
Cust_Name = dr["CUS_Name_V"].ToString(),
Pay_Amount = dr["REC_PaidAmount_M"].ToString(),
Pay_Mode = dr["REC_PayMode_C"].ToString(),
Bank_Name = dr["REC_BankName_V"].ToString(),
Bank_Address = dr["REC_BankAddress"].ToString(),
ChequeNo = dr["REC_ChequeNo_V"].ToString(),
Cheque_Date = dr["REC_ChequeDate_D"].ToString(),
Date = Convert.ToDateTime(dr["REC_Date_D"].ToString()),
});
}
return ReceiptList;
}
You can Use PartialView to bind Data in Web grid, I used this code:
Script:
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.get('#Url.Action("SelectCustomerByID", "Admin")', { secondValue: firstDDLValue }, function (ReceiptList) {
$('#gridContent').html(ReceiptList);
});
});
});
</script>
Controller:
`public ActionResult SelectCustomerByID(Receipt model, string secondValue)
{
//Receipt Recepit = new Receipt();
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
if(CustID!=0)
ReceiptList = Receipt.GetReceiptListByCustID(CustID);
else
ReceiptList = Receipt.GetReceiptList();
ViewData["Count"] = ReceiptList.Count;
return PartialView("_Recepitgrid", ReceiptList);
}

C# array to MVC view for Google Map markers

I am having such a rough time accomplishing this and all the research I'm doing is not turning out positive. In short, I need to send an array of markers from my code to my MVC view (through the model and setting it as a hidden field) so that the Google map can use this array to place markers on the map. I have tried building it as a List and then using JSON serialization to turn it to a string, but the format just won't turn out and won't be recognizable to the Google API. Has anyone done this before successfully??
Here is my updated code based on CodeMonkey's answer, but the markers still aren't placing. I think it's happening somewhere in the addMarker function...
var lat = $("#Latitude").val();
var lng = $("#Longitude").val();
var myOptions = {};
var map = null;
var marker = null;
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function map_initialize() {
var myLatlng = new google.maps.LatLng(lat, lng);
myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
#foreach (var item in Model.AllSearchResults)
{
<text>try
{
var lat = '#item.Latitude';
var lng = '#item.Longitude';
var name = '#item.Name';
var url = '#Url.Action("GetMarker", "Base")';
var model = { "Latitude": lat, "Longitude": lng, "Name": name };
$.ajax({
type: "POST",
data: model,
dataType: "json",
url: url,
success: function (data) {
geodata = data;
JSONString = JSON.stringify(geodata);
var valuesToPush = new Array();
valuesToPush[0] = data.Latitude;
valuesToPush[1] = data.Longitude;
valuesToPush[2] = data.Name;
markers.push(valuesToPush);
addMarker();
},
error: function () {
alert("fail");
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var name = markers[i][2];
var location = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + name + '</p></div>';
var marker = new google.maps.Marker({
position: location,
map: map,
title: name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', map_initialize);
I was able to do a combo server side/client side approach using the following link as a guide: http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html
Thanks for Code Monkey's input!!
You can reference my front-end JS code at this URL: http://www.wallodex.com/WallodexAdmin/Map/10
This is how I use it on the VIEW:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CloudClaims Administration - Site Visits</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgJDbn0VP_AnX4HsXSjN3cIn0MoEJ4vOw&sensor=false"></script>
<script type="text/javascript" src="../../js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../../js/json2.js"></script>
<script type='text/javascript'>
var DISPLAY_COUNT = 20;
var myOptions = {};
var markerArray = new Array();
var map = null;
//var geocoder = null;
var marker = null;
var g_ctr = 0;
var last_used_address = "";
var splitURLs = {};
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function initialize() {
myOptions = {
center: new google.maps.LatLng(38.5111, -96.8005),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//geocoder = new google.maps.Geocoder();
#foreach (var item in Model)
{
<text>try
{
var ip = '#item';
var url = 'http://api.ipinfodb.com/v3/ip-city/?format=json&key=6d0759103a4ec817ffda18dfba4eafe853125d6960dedffdcfa4a428774d871d&ip=' + ip + '&callback=?';
$.getJSON(url,
function (data) {
if (data['statusCode'] == 'OK') {
geodata = data;
JSONString = JSON.stringify(geodata);
//callback();
//alert(data.regionName);
var valuesToPush = new Array();
valuesToPush[0] = data.latitude;
valuesToPush[1] = data.longitude;
valuesToPush[2] = data.cityName + ', ' + data.regionName;
valuesToPush[3] = data.ipAddress;
markers.push(valuesToPush);
addMarker();
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var cityState = markers[i][2];
var ipAddress = markers[i][3];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + cityState + '<br/>' + ipAddress + '</p></div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " \n Location: " + cityState
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fadeInbox").hide().fadeIn(4000);
$("#map_canvas").hide().fadeIn(4000);
$(".subscriberList").hide().fadeIn(8000);
});
$(window).load(function () {
$("#loading").css('visibility', 'hidden');
});
</script>
<style type="text/css">
.infowindow
{
background-color: Yellow;
text-align: left;
padding: 0px, 0px, 0px, 0px;
margin: 0px, 0px, 0px, 0px;
}
.fadeOutbox, .fadeInbox, .fadeTobox
{
padding: 10px;
margin: 4px;
border: 1px solid blue;
width: 250px;
height: 50px;
background-color: #000000;
color: white;
font: georgia;
}
.clear
{
clear: both;
}
</style>
</head>
<body onload="initialize();">
<form id="form1" runat="server">
<asp:panel id="Panel1" runat="server" style="height: 600px;">
<asp:Literal ID="js" runat="server"></asp:Literal>
<table width="100%" align="center" border="1">
<tr bgcolor="#1569C7" align="center">
<td colspan="2">
<font color="white">CloudClaims™ - Site visitors - Last X days</font>
</td>
</tr>
<tr align="center">
<td width="80%">
<div id="map_canvas" style="width: 100%; height: 620px; margin-bottom: 0.5px;"></div>
</td>
<td align="center" valign="bottom" bgcolor="#FFBD82">
<asp:Label runat="server" id="errors"/>
<div>
#{Html.RenderAction("Subscribers");}
</div>
<div align="center" class="fadeInbox">
<b>DEBUGGING</b><br />
<asp:Label runat="server" id="ajaxtest"/>
</div>
</td>
</tr>
</table>
</asp:panel>
</form>
</body>
</html>
And this is my CONTROLLER (I convert IP ADDRESSES to gMap objects on the front-end but you get the idea...):
public ActionResult Map(int id)
{
try
{
using (var db = new CloudClaimsEntities())
{
DateTime dateFrom = (id != null && id > 1) ? DateTime.Now.AddDays(-id) : DateTime.Now.AddDays(-1);
List<string> IPAddresses = new List<string>();
IPAddresses = db.IPLogs
.Where(i => i.timeStamp <= DateTime.Now)
.Where(i => i.timeStamp >= dateFrom)
.Select(i => i.IPAddress)
.ToList();
return View(IPAddresses);
}
}
catch
{
return View();
}
}

Categories