PagedListRenderOptions : How can I add FunctionToTransformEachPageLink page-link class? - asp.net-mvc

I need help for asp.net;
When I add this class as below, my list defines html tags as strings.
#Html.PagedListPager(Model, page =>
Url.Action("Index", new { page = page }),
new PagedListRenderOptions
{
UlElementClasses = new string[] { "pagination pagination-xs pagination-gutter pagination-warning" },
LiElementClasses = new string[] { "page-item" },
LinkToPreviousPageFormat = "Geri",
LinkToNextPageFormat = "İleri",
ClassToApplyToLastListItemInPager = "page-previus",
ClassToApplyToFirstListItemInPager = "page-next",
FunctionToTransformEachPageLink = (li, a) =>
{
a.AddCssClass("page-link");
li.SetInnerText(a.ToString());
return li;
}
})
How can I fix it :
<a not working html tag => <a class="page-link"
<ul class="pagination pagination-xs pagination-gutter pagination-warning">
<a class="page-link">1</a>
<a class="page-link" href="/Device?page=2">2</a>
<a class="page-link" href="/Device?page=2" rel="next">İleri</a>

I fixed : li.InnerHtml = a.ToString();
#Html.PagedListPager(Model, page =>
Url.Action("Index", new { page = page }),
new PagedListRenderOptions
{
UlElementClasses = new string[] { "pagination pagination-xs pagination-gutter pagination-warning" },
LiElementClasses = new string[] { "page-item" },
LinkToPreviousPageFormat = "Geri",
LinkToNextPageFormat = "İleri",
ClassToApplyToLastListItemInPager = "page-previus",
ClassToApplyToFirstListItemInPager = "page-next",
FunctionToTransformEachPageLink = (li, a) =>
{
a.AddCssClass("page-link");
li.InnerHtml = a.ToString();
return li;
}
})

Related

net mvc: posting calculated date not working

I have an app where users get three suggestions for their order as datetime:
Don´t worry about the year, just an example.
If none of the suggestions fit users can generate three other suggestions in the future, based on the latest calculated date.
This works only once.
My View:
#using (Ajax.BeginForm("GenerateSuggestionDates", "Home", new { Area = "Planning" }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "planeditbody" }, new { autocomplete = "off", id = "suggestiondatesform" }))
{
#Html.HiddenFor(model => model.LatestDate)
#Html.HiddenFor(model => model.AssemblyOrderID)
<i class="fa fa-refresh mt-2 mr-3" style="float: right; color: grey; cursor: pointer;" onclick="$('#suggestiondatesform').submit();"></i>
}
Model.LatestDate is always set to the latest date in controller, but that latest date works only once.
My Controller:
[HttpPost]
public ActionResult GenerateSuggestionDates(PlanEditSingleViewModel model)
{
var viewModel = new PlanEditSingleViewModel();
Dictionary<int, DateTime> suggestions = new Dictionary<int, DateTime>();
try
{
var date = model.LatestDate.AddDays(1);
var counter = 0;
while (counter >= 0 && counter < 3)
{
if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
{
suggestions.Add(counter, planningService.CheckDesiredDate(date, true, model.AssemblyOrderID, null, true)[0]);
date = date.AddDays(1);
counter++;
}
else
{
date = date.AddDays(1);
}
}
viewModel.Suggestions = suggestions;
viewModel.LatestDate = date.AddDays(-1);
viewModel.AssemblyOrderID = model.AssemblyOrderID;
return PartialView("~/Views/Shared/Modals/PlanEditBodySingle.cshtml", viewModel);
}
catch (Exception e)
{
return PartialView("~/Views/Shared/Modals/PlanEditBodySingle.cshtml", null);
}
}
I can´t find what´s wrong here. Any hints, tipps, suggestions?
Thanks in advance!
Something seemed to be wrong with the binding (?).
I changed the code to this:
#using (Ajax.BeginForm("GenerateSuggestionDates", "Home", new { Area = "Planning", LatestDate = Model.LatestDate.ToString(), AssemblyOrderID = Model.AssemblyOrderID }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "planeditbody" }, new { autocomplete = "off", id = "suggestiondatesform" }))
{
<i class="fa fa-refresh mt-2 mr-3" style="float: right; color: grey; cursor: pointer;" onclick="$('#suggestiondatesform').submit();"></i>
}
Accordingly I edited the controller code. This works.

Unable to update model on calendar date change

I am having an issue with the angular ui bootstrap datepicker popup (https://angular-ui.github.io/bootstrap/) where I cannot get my model to update.
I have in place 2 different calendars - one with the popup and one without (uib-datepicker-popup and uib-datepicker) inside one of my angular component.
This is my code:
function headerCtrl () {
const self = this;
self.$onInit = () => {
self.dateOptions = {
showWeeks: false,
formatYear: 'yyyy',
startingDay: 1
};
self.today = function() {
self.calendar_date2 = new Date();
};
self.today();
self.clear = function() {
self.calendar_date2 = null;
};
self.inlineOptions = {
customClass: getDayClass,
minDate: new Date(),
showWeeks: true
};
self.toggleMin = function() {
self.inlineOptions.minDate = self.inlineOptions.minDate ? null : new Date();
self.dateOptions.minDate = self.inlineOptions.minDate;
};
self.toggleMin();
self.open = function() {
self.popup.opened = true;
};
self.setDate = function(year, month, day) {
self.calendar_date2 = new Date(year, month, day);
};
self.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
self.format = self.formats[0];
self.altInputFormats = ['M!/d!/yyyy'];
self.popup = {
opened: false
};
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 1);
self.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
function getDayClass(data) {
var date = data.date,
mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i = 0; i < self.events.length; i++) {
var currentDay = new Date(self.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return self.events[i].status;
}
}
}
}
self.changeCalendarDate = () => {
console.log('changeCalendarDate');
console.log(self.calendar_date);
};
self.changeCalendarDate2 = () => {
console.log('changeCalendarDate2');
console.log(self.calendar_date2);
};
}}
export default {
bindings: {
duration: "<",
zoom: "<",
selection: "<",
selections: "<",
calendar_date: "<",
onDurationChange: "&",
onCalendarDateChange: "&",
onHeatmapSelectionChange: "&"
},
controller: headerCtrl,
template: `
<div class="pp-header-container">
<div uib-datepicker
ng-model="$ctrl.calendar_date"
datepicker-options="$ctrl.dateOptions"
class="heatmap-header pp-sch-header-item"
ng-change="$ctrl.changeCalendarDate()"></div>
<div class="pp-header-calendar">
<input type="text"
uib-datepicker-popup="{{$ctrl.format}}"
ng-model="$ctrl.calendar_date2"
is-open="$ctrl.popup.opened"
datepicker-options="$ctrl.dateOptions"
ng-required="true"
close-text="Close"
alt-input-formats="$ctrl.altInputFormats"
maxlength="10"
size="10"
ng-change="$ctrl.changeCalendarDate2()" />
<button type="button" class="btn btn-default" ng-click="$ctrl.open()"><i class="glyphicon glyphicon-calendar"></i></button>
</div>
</div>`
}
http://prnt.sc/esq9c9
The calendar on the left (uib-datepicker) works, as soon as I pick a date, it triggers changeCalendarDate() and it prints the selected date (console.log(self.calendar_date);)
Now what I am trying to do is change calendar as I would like the one with the popup ( uib-datepicker-popup ) which does trigger changeCalendarDate2() but when I print the value (console.log(self.calendar_date2);) it is undefined.
I am sure I need to grab that value differently but I don't know how.
Can anyone help?
Thanks :)
I have solved this problem :D
The problem was this
uib-datepicker-popup="{{$ctrl.format}}"
as soon as I have removed thee value assigned and left only
uib-datepicker-popup
it worked. I don't know why but I am happier now :)

How to delete multiple records in a webgrid by clicking a delete button which is declared in a partial view in MVC

I have declared the webgrid inside a div in a partial view and my delete button is in Main View.Now I want a functionality in which when i click the delete button my webgrid should get refreshed only not whole page(Main View).
**I want to refresh only partial View which Contains webgrid using jquery in mvc
My partial View Code is as follows:
WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station");
//WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station", ajaxUpdateContainerId: "grid1");
string Message = "";
if (#ViewBag.NoData != null)
{
Message = ViewBag.NoData.ToString();
}
<div id="UserMainDiv">
#if (Model.Count() > 0)
{
<div id="grid1" class="row container" style="width:84%;margin-left:8%;">
<div class="col-md-12" style="width:100%;color:black;margin-top:10px;padding-left:0px;padding-right:0px;">
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
tableStyle: "webgrid",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
//mode: WebGridPagerModes.All,
//firstText: "",
//lastText: ">>",
//previousText: "<",
//nextText: ">",
columns: grid.Columns
(
//Here I am going to add checkbox column
//Here I am going to add checkbox column
grid.Column(format: #<text> <input type="checkbox" value="#item.ID" name="ids" /> </text>, header: "{checkall}"),
//grid.Column("ID"),
#*grid.Column("Name",format: #<text>#Html.ActionLink((string)item.Name, "AddEdit", "gridchk", new { id = item.id })</text>),*#
grid.Column("Station", format: #<text>#Html.ActionLink((string)item.Station, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
grid.Column("FlightNo", "Flight No", format: #<text>#Html.ActionLink((string)item.FlightNo, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
grid.Column("FlightDate", "Flight Date", format: #<text>#Html.ActionLink((string)item.FlightDate.ToString("MM/dd/yy"), "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("FlightDate", "Flight Date", format: (item) => item.FlightDate != null ? item.FlightDate.ToString("MM/dd/yy") : "NULL"),
grid.Column("PaxNo", "Pax No", format: #<text>#Html.ActionLink((string)item.PaxNo != null ? (string)item.PaxNo : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("PaxNo", "Pax No", format: (item) => item.PaxNo != null ? item.PaxNo : "NULL"),
grid.Column("PaxNoOwnward", "PaxNo Onward", format: #<text>#Html.ActionLink((string)item.PaxNoOwnward != null ? (string)item.PaxNoOwnward : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("PaxNoOwnward", "PaxNo Onward", format: (item) => item.PaxNoOwnward != null ? item.PaxNoOwnward : "NULL"),
grid.Column("TextMsg", format: #<text>#Html.ActionLink((string)item.TextMsg, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>)
)
)
</div>
</div>
}
#*</div>*#
else
{
<div style="width:80%;margin-left:10%;">
<div class="row container">
<div class="col-md-12" style="width:100%;color:black;margin-top:10px;text-align:center;">
#Html.Label("", Message, new { id = "lblMessage" })
</div>
</div>
</div>
}
</div>
And My Main page view where i have delete button button code declared.
With that I am using Jquery
$('#btnDelete').click(function (e) {
var command = $('#btnDelete').val();
var myArray = [];
$("#gridtable tbody tr td:nth-child(1)").find('input[type="checkbox"]:checked').each(function () {
myArray.push(($(this).val()));
});
e.preventDefault();
var url = '#Url.Action("DeleteUser", "CreateUser")';
$.ajax({
url: url,
type: 'GET',
data: { ids: myArray },
dataType: 'html',
success: function (data) {
// $("#demoaArea").html(data);
location.reload();
// window.location.href = url;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error; ' + eval(error));
alert("Status: " + textStatus); alert("Error: " + errorThrown);
//alert('Error!');
}
});
});
My Delete controller code:
public Actionresult DeleteStudent(int ids)
{
// delete the record from ID and return true else false
}
In your ajax call success, instead of reload , use the below one.
$('#UserMainDiv').html(data)
and in your controller return partialview instead of whole view.
public Actionresult DeleteStudent(int ids)
{
// delete the record from ID and return true else false
return PartialView("PartialViewName",model);
}

Pass webgrid data back to controller via post asp.net mvc

I am new to MVC and would like to know, how to submit whole grid data on submit button click to controller at once using viewmodel.
In View
#model prjMVC4Training.Models.BookViewModel
#{
ViewBag.Title = "Index";
var categories = ViewBag.BookCategories;
var authors = ViewBag.BookAuthors;
var grid = new WebGrid(source: Model.BookData, canSort: true, canPage:true);
}
#using (Html.BeginForm("BookPost", "Book", FormMethod.Post, new { #id = "grid" }))
{
<h2>Book Index Page</h2>
#Html.HiddenFor(m => m.PrimaryKeyID)
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns(
grid.Column("Actions",
style: "col1",
canSort: false,
format: #<text>
<button type="button" class="edit-book display-mode" id="#item.BookID">Edit</button>
<button type="button" class="save-book edit-mode" id="#item.BookID">Save</button>
<button type="button" class="cancel-book edit-mode" id="#item.BookID">Cancel</button>
</text>),
grid.Column("BookTitle",
style: "col2",
canSort: true,
format: #<text>
<span id="dBookTitle" class="display-mode">#item.BookTitle</span>
#Html.TextBox("BookData_" + (int)item.BookID + "__BookID", (string)item.BookTitle, new { #class = "edit-mode", size = 45 })
</text>),
grid.Column("AuthorName",
header: "Author",
style: "col3",
canSort: true,
format: #<text>
<span id="dAuthorName" class="display-mode">#item.AuthorName</span>
#Html.DropDownList("AuthorID_" + (int)item.BookID, (ViewBag.BookAuthors as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.AuthorID
}), new { #class = "edit-mode" })
</text>),
grid.Column("CategoryName",
style: "col4",
canSort: true,
format: #<text>
<span id="dCategoryName" class="display-mode">#item.CategoryName</span>
#Html.DropDownList("CategoryID_" + (int)item.BookID, (ViewBag.BookCategories as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.CategoryID
}), new { #class = "edit-mode" })
</text>),
grid.Column("BookISBN",
style: "col5",
format: #<text>
<span id="dBookISBN" class="display-mode">#item.BookISBN</span>
#Html.TextBox("BookISBN_" + (int)item.BookID, (string)item.BookISBN, new { #class = "edit-mode", size = 20 })
</text>),
grid.Column("IsMember",
style: "",
format: #<text>
<span id="dMember" class="display-mode">#item.IsMember</span>
<input type="checkbox" id="MemberID_" + (int)item.BookID name="MemberID" #(item.IsMember == true ? "Checked" : null) class="edit-mode"/>
</text>)))
<button type="submit" value="Save Book Data">Save Book Data</button>
}
On submit button, I want to pass the value to controller
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BookPost(BookViewModel obj)
{
ViewBag.BookCategories = new SelectList(BookHelperData.GetBookCategories(), "CategoryID", "CategoryName", "20");
ViewBag.BookAuthors = new SelectList(BookHelperData.GetAuthors(), "AuthorID", "AuthorName");
//ViewBag.BookAuthors = BookHelperData.GetAuthorsList();
var Book = BookHelperData.GetBooks();
return View(Book);
}
My ViewModel Class is like this-
public class BookViewModel
{
public int PrimaryKeyID { get; set; }
public List<Book> BookData { get; set; }
}
You can write a generic method which loops all the data in grid and transform it to json structure.
function gridTojson() {
var json = '{';
var otArr = [];
var tbl2 = $('#employeeGrid tbody tr').each(function (i) {
if ($(this)[0].rowIndex != 0) {
x = $(this).children();
var itArr = [];
x.each(function () {
if ($(this).children('input').length > 0) {
itArr.push('"' + $(this).children('input').val() + '"');
}
else {
itArr.push('"' + $(this).text() + '"');
}
});
otArr.push('"' + i + '": [' + itArr.join(',') + ']');
}
})
json += otArr.join(",") + '}'
return json;
}
Now on submit button click you need to pass the data to controller.
$('#btnsave').click(function (e) {
//debugger;
var _griddata = gridTojson();
var url = '#Url.Action("UpdateGridData")';
$.ajax({
url: url,
type: 'POST',
data: { gridData: _griddata }
}).done(function (data) {
if (data != "") {
$('#message').html(data);
}
});
});
Now on controller serialize the data back
public ActionResult UpdateGridData(string gridData)
{
var log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
return Json("Update Successfully");
}
Here is the post regarding this.

MVC 3 Webgrid with dropdownlist, get selected value on postback

I have a webgrid with dropdownlist and onchange it postback the page. I am trying to get the selected value of the dropdownlist.
Following is my Controller.
public ViewResult Index()
{
//var albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre);
var model = new AlbumActionModel { Actions = new[] { new SelectListItem { Text = "Accept", Value = "Accept" }, new SelectListItem { Text = "Deny", Value = "Deny" } }, Albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre) };
return View(model);
}
Following is my View.
<div>
#{
WebGrid grid = new WebGrid(Model.Albums, defaultSort: "Title", selectionFieldName: "SelectedRow");
}
#using (Html.BeginForm("Index", "Album", FormMethod.Post, new { id = "TheForm" }))
{
#grid.GetHtml(columns: grid.Columns(grid.Column("Edit",
format: #<text> #Html.ActionLink("Edit", "Edit", new { id = item.AlbumId })></text>),
grid.Column("AlbumId"),
grid.Column("Title"),
grid.Column("Action",
format:
#<span>
#{var index = item.AlbumId.ToString();}
#Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--", new { onchange = "this.form.submit();" })
</span>),
grid.Column("Delete",
format: #<text> #Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })></text>)))
</div>
Thanks in advance.
In your dropdownlist try the following statement:
#Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--",new { #onchange = "Submit(this.value);" })
Now write a function in your <script> tag to post it to the page
<script type="text/javascript">
function Submit(e)
{
//write it to post to the controller using ajax
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("Submit", "ControllerName")',
data: ({ value: e}),
success: function (result) {
//do something
}
,
error: function (result) {
//do something
}
});
}
</script>
Hope this helps.

Resources