I have a Layout page and a PartialView.
I have a search-button on the layout page and an update-button in a table in the partial view.
Once I click the search-button the update-button stops working. It works fine until I search. I'm guessing it has to do with the forms and actionresult but I can't get it to work. The actionresult is never reached - "nothing" happens.
Controller - RegisterTruckUser
[HttpPost]
public ActionResult RegisterTruckUser(string registerName, string registerPassword, string employeeNumber, string userTeam)
{
var model = new RegisterModel
{
UserList = db.SearchTruckUsers(""),
UserTeamList = GetUserTeamList(),
TriggerOnLoad = true
};
//If the Save button is clicked the user is updated
if (Request.Form.AllKeys.Contains("btnupdateuser"))
{
if (!Request["btnupdateuser"].IsEmpty())
{
Name = Request.Form["item.Name"];
password = Request["item.Password"];
EmployeeNumber = Request["item.EmployeeNumber"];
Userteam = Request["item.UserTeam"];
db.UpdateTruckUser(Name, password, EmployeeNumber, Userteam);
model.UserList = db.SearchTruckUsers("");
return PartialView(model);
}
}
ModelState.Clear();
return View(model);
}
model.TriggerOnLoadMessage = ErrorMessage;
return View(model);
}
Controller - SearchPartialView
[HttpPost]
public PartialViewResult SearchPartialView(string searchUserString)
{
if (Session["myID"] == null)
{
ExpireSession();
}
if (!ModelState.IsValid)
RedirectToLogin();
if (searchUserString.Any(char.IsDigit))
{
var model1 = new RegisterModel
{
TriggerOnLoad = false,
UserList = db.SearchTruckUsersEmpNum(searchUserString),
UserTeamList = GetUserTeamList()
};
return PartialView("_RegisterTruckUserPartialView", model1);
}
var model = new RegisterModel
{
TriggerOnLoad = false,
UserList = db.SearchTruckUsers(searchUserString),
UserTeamList = GetUserTeamList()
};
return PartialView("_RegisterTruckUserPartialView", model);
}
RegisterLayout
#model Name.Models.RegisterModel
<!DOCTYPE html>
<html lang="en">
<head>
<title>#ViewBag.Title - Register</title>
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
</head>
<body>
#RenderPage("~/Views/Shared/_Header.cshtml")
#RenderBody()
<div class="center" id="top">
<div id="search" class="active">
<h1>Manage users</h1>
#using (Ajax.BeginForm("SearchPartialView", "Register", null,
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divUsers",
}, new
{
id = "usertable"
}))
{
#Html.TextBox("SearchUserString", null, new { #class = "responsivetextbox", #placeholder = "Search username or employment number" })
<p>
<input type="submit" class="standardbutton logsearch" name="submit" value="Search" />
</p>
}
<div id="divUsers">
#{Html.RenderPartial("_RegisterTruckUserPartialView");}
</div>
</div>
</div>
#RenderPage("~/Views/Shared/_Footer.cshtml")
</body>
</html>
PartialView (table)
<table class="centeredTable">
<thead>
<tr>
<th>Name</th>
<th>Password</th>
<th>Employment Number</th>
<th>Team</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.UserList)
{
using (Html.BeginForm())
{
<tr id="usertabletr1">
<td id="usertabletd1">
#Html.EditorFor(modelItem => item.Name, new {htmlAttributes = new {#name = "test1", #style = "border: 0px none;"}})
</td>
<td id="usertabletd1">
#Html.EditorFor(modelItem => item.Password, new {htmlAttributes = new {#name = "registerPassword", #type = "password", #style = "border: 0px none; "}})
</td>
<td id="usertabletd1">
#Html.EditorFor(modelItem => item.EmployeeNumber, new {htmlAttributes = new {#name = "employeeNumber", #readonly = "readonly", #style = "border: 0px none; background: white;"}})
</td>
<td id="usertabletd1">
#Html.DropDownListFor(modelItem => item.UserTeam, Model.UserTeamList, item.UserTeam, new {htmlAttributes = new {#name = "Team", #style = "border: 0px none;"}})
</td>
<td id="usertabletd1">
<input class="standardbutton adddefaultvaluesubmit" type="image" src="~/Pictures/saveicon.ico" alt="Save" value="Save" name="btnupdateuser"/>
<input class="standardbutton adddefaultvaluesubmit" type="image" src="~/Pictures/trashcanicon.ico" alt="Delete" value="Delete" name="btndeleteuser"/>
</td>
</tr>
}
}
</tbody>
</table>
In your partial view it should look something like this.
<input type="button" value="Confirm team change" class="btnConfirm"/>
And then you add this to your "main" layout.
$(document).on('click', '.btnConfirm', function(){
$.ajax({
url: '#Url.Action("RegisterTruckUser", "Register")',
type: 'POST',
cache: false,
async: true,
data: $('form').serialize(),
success: function(result){
//do something
}
});
});
Related
I have been trying to create a the ability to add/edit records through the use of a modal in .net core.
I have been trying tutorials such as
https://www.youtube.com/watch?v=QmNtbnUfns8
https://www.mindstick.com/Articles/12723/crud-operation-modal-popup-uses-bootstrap-in-mvc
Neither of these are working for as they are as .net. The modal isnt showing up.
ViewClients.cshtml
#model IEnumerable<Evol.Models.Clients>
#{
ViewData["Title"] = "Clients";
Layout = "~/Views/Shared/_Layout.cshtml";
<div class="card">
<div class="card-header card-header-text card-header-rose">
<div class="card-text">
<h4 class="card-title">Clients</h4>
<p class="card-category"></p>
</div>
</div>
<div class="card-body table-responsive">
<div class="table-responsive">
<table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
<thead class="text-gray">
<tr>
<th>
#Html.DisplayNameFor(model => model.ClientName)
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(model => item.ClientName)
</td>
<td class="text-right">
<i class="material-icons">edit</i>
<button type="button" rel="tooltip" title="Remove" class="btn btn-
danger btn-link btn-sm">
<i class="material-icons">close</i>
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="myModal1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">AddEdit Employee</h3>
</div>
<div class="modal-body" id="myModalBodyDiv1">
</div>
</div>
</div>
</div>
<script>
var EditClient = function (ClientID) {
var url = "/Client/EditClient?ClientID=" + ClientID;
$("#myModalBodyDiv1").load(url, function () {
$("#myModal1").modal("show");
})
}
EditClient.cshmtl (partial view)
#model Evol.Models.Clients
<form id="myForm">
#Html.HiddenFor(m => m.ClientID)
#Html.TextBoxFor(model => model.ClientName, new { #class = "form-control", #placeholder = "Name" })
<a href="#" id="btnSubmit" class="btn btn-success btn-block">
#if (Model.ClientID > 0)
{
<span>Update</span>
}
else
{
<span>Save</span>
}
</a>
</form>
Add Client
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
$("#loaderDiv").show();
var myformdata = $("#myForm").serialize();
alert("Success")
$.ajax({
type: "POST",
url: "/Client/ViewClients",
data: myformdata,
success: function () {
$("#loaderDiv").hide();
$("#myModal1").modal("hide");
}
})
})
})
ClientContoller
public IActionResult EditClient(int ClientID)
{
Clients client = new Clients();
if(ClientID > 0)
{
var user = _context.ClientTable.SingleOrDefault(x => x.ClientID == clientID);
client.ClientID = user.ClientID;
client.ClientName = user.ClientName;
}
return PartialView("EditClient", client);
}
}
Did You Created DbContext Class In Your Project?
CRUD Operations In ASP.NET Core Using Entity Framework Core Code First
EF Core DbContext Class Sample
below code just sample for show data and edit or add data to table.
[HttpGet]
public IActionResult AddEditCustomer(long? id)
{
CustomerViewModel model = new CustomerViewModel();
if (id.HasValue)
{
Customer customer = context.Set<Customer>().SingleOrDefault(c => c.Id == id.Value);
if (customer != null)
{
model.Id = customer.Id;
model.FirstName = customer.FirstName;
model.LastName = customer.LastName;
model.MobileNo = customer.MobileNo;
model.Email = customer.Email;
}
}
return PartialView("~/Views/Customer/_AddEditCustomer.cshtml", model);
}
[HttpPost]
public ActionResult AddEditCustomer(long? id, CustomerViewModel model)
{
try
{
if (ModelState.IsValid)
{
bool isNew = !id.HasValue;
Customer customer = isNew ? new Customer
{
AddedDate = DateTime.UtcNow
} : context.Set<Customer>().SingleOrDefault(s => s.Id == id.Value);
customer.FirstName = model.FirstName;
customer.LastName = model.LastName;
customer.MobileNo = model.MobileNo;
customer.Email = model.Email;
customer.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
customer.ModifiedDate = DateTime.UtcNow;
if (isNew)
{
context.Add(customer);
}
context.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("Index");
}
This is because you are missing the HTTP Post attribute PLEASE SEE the docs here
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1
[HTTPPOST]
public IActionResult EditClient(int ClientID)
{
Clients client = new Clients();
if(ClientID > 0)
{
var user = _context.ClientTable.SingleOrDefault(x => x.ClientID == clientID);
client.ClientID = user.ClientID;
client.ClientName = user.ClientName;
}
return PartialView("EditClient", client);
}
}
I'm working on a page that will add the selected item from a dropdownlist to a List<> using button onclick.
The problem is the new selecteditem is overwriting the old value.
I simply would like to display a table from the selected items like this:
#---Model-----Remove-----
1 Model#1 x
2 Model#2 x
3 Model#3 x
4 Model#4 x
5 Model#5 x
-------------------------
Please see my code below,
ModelDescription.cs (model):
public class ModelDescription
{
public string modelDesc { get; set; }
}
method in controller:
public ActionResult StockOnHand()
{
bindModelDesc();
return View();
}
public void bindModelDesc()
{
var mc = db.ModelMaster_tbl.ToList();
List<SelectListItem> mclist = new List<SelectListItem>();
mclist.Add(new SelectListItem { Text = "--Select Model Type--", Value = "0" });
mclist.Add(new SelectListItem { Text = "--Select All Model--", Value = "1" });
foreach (var m in mc.Select(x => x.modelDesc).Distinct())
{
mclist.Add(new SelectListItem { Text = m, Value = m });
ViewBag.ModelDescs = mclist;
}
}
public ActionResult AddToListSOH(ModelDescription model)
{
var result = new List<ModelDescription>();
var res = db.ModelMaster_tbl.Where(x => x.modelDesc == model.modelDesc).SingleOrDefault();
result.Add(new ModelDescription { modelDesc = res.modelDesc });
return PartialView("AddToListSOH", result);
}
StockOnHand.cshtml (view):
#using (Html.BeginForm("StockOnHand", "PWSupermarket", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="card">
<div class="card-body">
<form class="form-horizontal" role="form">
<h5 class="card-title">Stock On Hand</h5>
<p class="card-text">Generates the buildable quantity of a unit. </p>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#if (TempData["Message"] != null)
{
<span class="text-success"><strong>#TempData["Message"]</strong></span>
}
<div class="form-group">
#Html.LabelFor(model => model.modelDesc, htmlAttributes: new { #class = "col-md-3 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.modelDesc, ViewBag.ModelDescs as List<SelectListItem>, htmlAttributes: new { #class = "form-control" })
<button class="btn btn-outline-primary mt-1" type="button" onclick="AddToList()">Add To List</button>
</div>
</div>
<div id="foo1" class="mt-2">
</div>
</form>
</div>
</div>
}
Javascript to render the list of selected items partial view:
<script type="text/javascript">
function AddToList() {
$.ajax({
type: "Get",
url: '#Url.Action("AddToListSOH", "PWSupermarket")',
data: { modelDesc: $('#modelDesc').val() },
contentType: "application/html; charset=utf-8",
success: function (result) {
$('#foo1').html(result);
},
error: function (ex) { alert('failed.'); }
})
}
</script>
AddToListSOH.cshtml (Partial View for the list of selected items):
#model IEnumerable<MESProject_P1_csmvc.Models.ModelDescription>
<div>
#{ var count = 0;}
<table class="table table-sm table-striped" #*style="font-size: .7rem;"*#>
<caption>List of Models</caption>
<thead class="thead-dark">
<tr>
<th>#</th>
<th>Model</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#count
</td>
<td>
#Html.DisplayFor(i => item.modelDesc)
</td>
</tr>
}
</tbody>
</table>
</div>
screen shot of the page
Example to make SelectListItem List
private List<SelectListItem> ModelDeskList(ModelDesk modelDesc)
{
List<SelectListItem> selectList = new List<SelectListItem>();
selectList.Add(new SelectListItem { Value = "", Text = "------Select-----",Selected=true });
foreach (var model in modelDesc)
{
selectList.Add(new SelectListItem { Value = model.Id.ToString(), Text = model.Name});
}
return selectList;
}
I hope you find your solution from it
I solved my problem thanks to this link:
I'm storing the list of emails in Session["emails"] and every time I add a new email to the list, I just update it a pass it to a new list with all the records and at the end return the partial view.
.NET use partial view multiple times #Rolando F
I've changed some of my codes:
ModelDescription.cs
public class ModelDescription
{
public IEnumerable<string> modelsAdded { get; set; }
}
AddToListSOH method in controller:
public ActionResult AddToListSOH(string model)
{
if (Session["modelInputs"] == null)
{
List<string> temphandler1 = new List<string>();
temphandler1.Add(model);
Session["modelInputs"] = temphandler1;
}
else
{
List<string> temphandler2 = new List<string>();
temphandler2 = (List<string>)Session["modelInputs"];
temphandler2.Add(model);
Session["modelInputs"] = temphandler2;
}
var result = new ModelDescription { modelsAdded = (List<string>)Session["modelInputs"] };
return PartialView("AddToListSOH", result);
}
AddToListSOH.cshtml (Partial View):
<table class="table table-sm table-striped" #*style="font-size: .7rem;"*#>
<caption>List of Models</caption>
<thead class="thead-dark">
<tr>
<th>#</th>
<th>Model</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.modelsAdded)
{
<tr>
<td>
#count
</td>
<td>
#Html.DisplayFor(i => item)
</td>
<td>
Remove
</td>
</tr>
}
</tbody>
</table>
I have got a problem as follows:
I have created a table with dynamic rows by clicking "add button".A row includes some textboxes and one dropdown list. When I select a value from dropdown list as a term to automatically fill for other textboxes by data I get from the server. Now I just can apply for the first row.I don't know how to apply for the new row when click "add button".Please help me how to solve this problem. Thanks a lot.
This is my webpage
This is my controller code:
using Phieu90.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Phieu90.Controllers
{
public class XuLyPhieuController : Controller
{
XuLyPhieu90Entities1 db;
public XuLyPhieuController()
{
db = new XuLyPhieu90Entities1();
}
public ActionResult Index()
{
var lislinhkien = new SelectList(db.PA_LINHKIEN.ToList(), "ITEM_CODE", "ITEM_CODE");
ViewBag.LinhKien = lislinhkien;
List<PA_CHITIETPHIEU> listchitiet = new List<PA_CHITIETPHIEU> { new PA_CHITIETPHIEU { NHACUNGCAP = "", TENSP = "", MASP = "", MADUTOAN = "", SOLUONG = 0, DONVI = "", DONGIA = 0, SOTIEN = 0 } };
return View(listchitiet);
}
[HttpPost]
public JsonResult GetLinhKien(string Prefix)
{
var result = db.PA_LINHKIEN.SingleOrDefault(x => x.ITEM_CODE == Prefix);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
This is my View:
<body>
<h2 style="text-align:center;margin-top:50px;margin-bottom:50px;">Bill Detail</h2>
#using (Html.BeginForm("PhieuMuaLinhKien", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div>Add New Row <i class="fas fa-plus-circle"></i></div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0" class="table table-bordered">
<tr>
<th class="title">Bill ID</th>
<th class="title">Supplier</th>
<th class="title">Item name</th>
<th class="title">Item code</th>
<th class="title">Reference code</th>
<th class="title">Quantity</th>
<th class="title">Unit</th>
<th class="title">Price</th>
<th class="title">Sum</th>
<th class="title">Delete</th>
</tr>
#if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr style="border:1px solid black">
<td class="title">#Html.TextBoxFor(a => a[j].MACHITIET, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required" })</td>
<td class="title">#Html.TextBoxFor(a => a[j].NHACUNGCAP, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required", #id = "txtncc" })</td>
<td class="title">#Html.TextBoxFor(a => a[j].TENSP, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required",#id= "txttensp" })</td>
#using (Html.BeginForm())
{
#*<td class="title">#Html.TextBoxFor(a => a[j].MASP, new { #class = "form-control view-data", #style = "width:120px;margin-left:12px;", #required = "required"})</td>*#
<td>#Html.DropDownListFor(a => a[j].MASP, ViewBag.LinhKien as SelectList, "--*--", new { #class = "form-control view-data", #style = "width:120px;margin-left:12px;", #required = "required",#id="ddllinhkien" })</td>
}
<td class="title">#Html.TextBoxFor(a => a[j].MADUTOAN, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required" })</td>
<td class="title">#Html.TextBoxFor(a => a[j].SOLUONG, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required" })</td>
<td class="title">#Html.TextBoxFor(a => a[j].DONVI, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required" })</td>
<td class="title">#Html.TextBoxFor(a => a[j].DONGIA, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required", #id = "txtdongia" })</td>
<td class="title">#Html.TextBoxFor(a => a[j].SOTIEN, new { #class = "form-control", #style = "width:120px;margin-left:12px;", #required = "required" })</td>
<td>
#if (j > 0)
{
Remove <i class="fas fa-trash"></i>
}
</td>
</tr>
j++;
}
}
</table>
}
<div style="margin-left:660px;margin-top:30px;">
<button type="submit" class="btn btn-primary" id="btnSubmit" style="">Save <i class="fas fa-save"></i></button>
</div>
enter code here
<script type="text/javascript">
$(document).ready(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone().insertAfter($trLast);
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('<a href="#" class="btn btn-block btn-
danger remove">Xóa <i class="fas fa-trash"></i></a>');
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' +
(parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
$(this).attr('id', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
var form = $("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});
//2. Remove
//$('a.remove').on("click", function (e) {
// e.preventDefault();
// $(this).parent().parent().remove();
//});
$("#dataTable").on("click", ".remove", function () {
$(this).closest('tr').remove();
});
$('.view-data').change(function () {
var malk = $(this).val();
$.ajax({
url: "/XuLyPhieu/GetLinhKien",
type: "POST",
dataType: "json",
data: { Prefix: malk },
success: function (data) {
//do something
})
}
})
})
});
I have issue while working with MVC.
while running application for the first time I am getting 20 results.On filter I am getting 4 results.I am able to see those 4 result in Model while debugging but on view its not getting updated. I tried ViewData and ViewBag also but the result is Same.
Can anyone help me out?
Following is My IncentiveGroupConroller.cs
public ActionResult IncentiveGroupIndex(int? page)
{
int pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
IPagedList<IncentiveGroup> PAGEDGROUP = null;
List<IncentiveGroup> IncentiveGroups = new List<IncentiveGroup>();
DataSet ds = new DataSet();
ds = SQLDatabaseOperations.ExecuteDataset(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), CommandType.StoredProcedure, "GetIncentiveGroups");
DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
IncentiveGroups.Add(new IncentiveGroup(dr));
}
ViewBag.IncentiveGroups = IncentiveGroups;
PAGEDGROUP = IncentiveGroups.ToPagedList(pageIndex, 10);
return View(PAGEDGROUP);
}
[HttpPost]
public ActionResult Filter(IncentiveGroup oIncentiveGroup)
{
IPagedList<IncentiveGroup> PagedIncenticeGroups = null;
List<IncentiveGroup> IncentiveGroups = new List<IncentiveGroup>();
DataSet ds = new DataSet();
ds = SQLDatabaseOperations.ExecuteDataset(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), CommandType.StoredProcedure, "FilterIncentiveGroups", oIncentiveGroup.IncentiveGroupCode, oIncentiveGroup.IncentiveGroupName, oIncentiveGroup.IncentiveGroupShortName, oIncentiveGroup.IncentiveGroupStatus);
DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
IncentiveGroups.Add(new IncentiveGroup(dr));
}
ViewBag.IncentiveGroups = IncentiveGroups;
PagedIncenticeGroups = IncentiveGroups.ToPagedList(1, IncentiveGroups.Count);
return View("IncentiveGroupIndex", PagedIncenticeGroups);
// return RedirectToAction("IncentiveGroupIndex", PagedIncenticeGroups);
}
Follwling ajax call is made for controller
function filterIncentiveGroup() {
var setIncentiveGroupStatus = $('input[name=IncentiveGroupStatus]:checked').val();
var Test = {
IncentiveGroupCode: $('#IncentiveGroupCode').val(),
IncentiveGroupName: $('#IncentiveGroupName').val(),
IncentiveGroupShortName: $('#IncentiveGroupShortName').val(),
IncentiveGroupStatus: setIncentiveGroupStatus,
};
$.ajax({
url: "/IncentiveGroup/Filter",
data: JSON.stringify(Test),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "html",
success: function (data) {
$('#myModal').modal('hide');
alert("Success");
},
error: function (errormessage) {
$('#myModal').modal('hide');
alert(errormessage.responseText);
}
});
};
Following is my IncentiveGroupIndex.cshtml
#using PagedList.Mvc
#model PagedList.IPagedList<MPISMVC.Models.IncentiveGroup>
#{
ViewBag.Title = "Incentive Group";
}
#*<h2>IncentiveGroupIndex</h2>*#
<div class="container-fluid" style="padding-top: 100px">
<div class="panel panel-primary">
<div class="panel-heading">Manage Incentive Group</div>
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<button type="button" id="create" class="btn btn-success"><span class="glyphicon glyphicon-plus"></span>Add</button>
<button type="button" id="filter" class="btn btn-dafault"><span class="glyphicon glyphicon-filter"></span>Filter</button>
</div>
<div class="col-md-7">
<div class="pagination">
#* Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount *# #Html.PagedListPager(Model, page => Url.Action("IncentiveGroupIndex", new { page }), new PagedListRenderOptions { DisplayEllipsesWhenNotShowingAllPageNumbers = true, MaximumPageNumbersToDisplay = 5, LinkToFirstPageFormat = "First", LinkToPreviousPageFormat = "Previous", LinkToNextPageFormat = "Next", LinkToLastPageFormat = "Last" })
</div>
</div>
<div class="col-md-1">
#*#Html.DropDownList("PageSize", new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 },{ "50", 50 }, { "100", 100 } }, "Key", "Value", Model.PageSize), new { #class = "form-control" })*#
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model[0].IncentiveGroupCode)
</th>
<th>
#Html.DisplayNameFor(model => model[0].IncentiveGroupName)
</th>
<th>
#Html.DisplayNameFor(model => model[0].IncentiveGroupShortName)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.IncentiveGroupCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.IncentiveGroupName)
</td>
<td>
#Html.DisplayFor(modelItem => item.IncentiveGroupShortName)
</td>
<td>
<button type="button" id="View" class="btn btn-sm btn-info" data-toggle="tooltip" title="View" onclick="details('#item.IncentiveGroupCode','View');"><span class="glyphicon glyphicon-eye-open"></span></button>
<button type="button" id="Edit" class="btn btn-sm btn-primary" data-toggle="tooltip" title="Edit" onclick="details('#item.IncentiveGroupCode','Edit');"><span class="glyphicon glyphicon-pencil"></span></button>
#*<button type="button" id="Delete" class="btn btn-sm btn-danger" data-toggle="tooltip" title="Delete" onclick="remove('#item.IncentiveGroupCode');"><span class="glyphicon glyphicon-trash"></span></button>*#
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#* <div class="row">
<div class="pagination" style="margin-left: 400px">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount #Html.PagedListPager(Model, page => Url.Action("IncentiveGroupIndex", new { page }))
</div>
</div>*#
</div>
</div>
</div>
image of filtered data count
I have implemented the "Contact Management ASP.NET MVC Application" with Razor view.
http://www.asp.net/mvc/tutorials/iteration-7-add-ajax-functionality-cs
Now I want to add Sorting and Searching functionality.
And Paging too.
snapshot: ->
http://www.freeimagehosting.net/daf63
I want to display the sorted and searched results inside the "green box", by click of a sort links and search button.
What changes do I need to perform?
My current Index Controller:
public ActionResult Index(int? id, string sortorder, string searchstring)
{
ViewBag.CurrentSort = sortorder;
ViewBag.disp = n2;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortorder) ? "Namedesc" : " ";
ViewBag.NameSortParma = String.IsNullOrEmpty(sortorder) ? "Nameasc" : " ";
ViewBag.NameSortParmb = String.IsNullOrEmpty(sortorder) ? "Namedescx" : " ";
ViewBag.NameSortParmc = String.IsNullOrEmpty(sortorder) ? "Nameascx" : " ";
if (sortorder != null || searchstring != null)
{
var matches = cmu.Contacts.Where(a => a.GroupId == (int)id);
var contacts = from s in matches
select s;
if (!String.IsNullOrEmpty(searchstring))
{
contacts = contacts.Where(s => s.FirstName.ToUpper().Contains(searchstring.ToUpper()) || s.LastName.ToUpper().Contains(searchstring.ToUpper()));
}
switch (sortorder)
{
case "Namedesc":
contacts = contacts.OrderByDescending(s => s.FirstName);
break;
case "Nameasc":
contacts = contacts.OrderBy(s => s.FirstName);
break;
case "Namedescx":
contacts = contacts.OrderByDescending(s => s.LastName);
break;
case "Nameascx":
contacts = contacts.OrderBy(s => s.LastName);
break;
}
return PartialView("SearchSort", contacts.ToList());
}
// Get selected group
var selectedGroup = _service.GetGroup(id);
if (selectedGroup == null)
return RedirectToAction("Index", "Group");
// Normal Request
if (!Request.IsAjaxRequest())
{
var model = new IndexModel
{
Groups = _service.ListGroups(),
SelectedGroup = selectedGroup
};
return View("Index", model);
}
return PartialView("ContactList", selectedGroup);
}
My Index View:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model New_Contact_Manager_with_Razor_View.Models.Validation.IndexModel
#using New_Contact_Manager_with_Razor_View.Helpers
<style type = "text/css">
#gallery {
border: 0.5px solid #1D0C16;
height: 150;
width: 150px;
display:inline-table;
border-spacing : 5px;
margin-bottom:5px;
border-style:outset;
}
</style>
<style type="text/css">
h1, h2, h3, h4, h5, h6, h7 {color:black}
</style>`
<script type="text/javascript">
function Showtdata(item) {
var elements = document.getElementsByClassName(item);
for (var i = 0, length = elements.length; i < length; i++) {
elements[i].style.visibility = "visible";
elements[i].style.display = "block";
}
}
function Cleartdata(item) {
var elements = document.getElementsByClassName(item);
for (var i = 0, length = elements.length; i < length; i++) {
elements[i].style.visibility = "hidden";
elements[i].style.display = "none";
}
}
</script>
<script type="text/javascript">
var _currentGroupId = -1;
Sys.Application.add_init(pageInit);
function pageInit() {
// Enable history
Sys.Application.set_enableHistory(true);
// Add Handler for history
Sys.Application.add_navigate(navigate);
}
function navigate(sender, e) {
// Get groupId from address bar
var groupId = e.get_state().groupId;
// If groupId != currentGroupId then navigate
if (groupId != _currentGroupId) {
_currentGroupId = groupId;
$("#divContactList").load("/Contact/Index/" + groupId);
selectGroup(groupId);
}
}
function selectGroup(groupId) {
$('#leftColumn li').removeClass('selected');
if (groupId)
$('a[groupid=' + groupId + ']').parent().addClass('selected');
else
$('#leftColumn li:first').addClass('selected');
}
function beginContactList(args) {
// Highlight selected group
_currentGroupId = this.getAttribute("groupid");
selectGroup(_currentGroupId);
// Add history point
Sys.Application.addHistoryPoint({ "groupId": _currentGroupId });
// Animate
$('#divContactList').fadeOut('normal');
}
function successContactList() {
// Animate
$('#divContactList').fadeIn('normal');
}
function failureContactList() {
alert("Could not retrieve contacts.");
}
</script>
#using New_Contact_Manager_with_Razor_View.Helpers
#{
ViewBag.Title = "Contacts";
}
<table>
<tr>
<td>
<h3>
<form>
<table>
<tr>
<td>
Display->      
<input type = "radio" value = "Display " name = "display" onclick= Showtdata("HD") />
</td>
</tr>
<tr>
<td>
Not Display->
<input type = "radio" value = "Not Display " name= "display" onclick= Cleartdata("HD") />
</td>
</tr>
</table>
</form>
</h3>
</td>
<td>
       
</td>
<td>
<b><strong>Sort :~> </strong></b>
<table>
<tr>
<td>
#Html.ActionLink("First Name Desc", "Index", new { sortorder = ViewBag.NameSortParm })
</td>
</tr>
<tr>
<td>
#Html.ActionLink("First Name", "Index", new { sortorder = ViewBag.NameSortParma })
</td>
</tr>
<tr>
<td>
#Html.ActionLink("Last Name desc", "Index", new { sortorder = ViewBag.NameSortParmb })
</td>
</tr>
<tr>
<td>
#Html.ActionLink("Last Name", "Index", new { sortorder = ViewBag.NameSortParmc })
</td>
</tr>
</table>
</td>
<td>
     
</td>
<td>
#using (Html.BeginForm())
{
<p>
<b>Find by name:</b> #Html.TextBox("searchstring")
<input type="submit" value = "search" />
</p>
}
</td>
</tr>
</table>
<ul id="leftColumn">
#foreach (var item in Model.Groups)
{
<li #Html.Selected(item.Id, Model.SelectedGroup.Id) >
#Ajax.ActionLink(item.Name, "Index", new { id = item.Id }, new AjaxOptions { UpdateTargetId = "divContactList", OnBegin = "beginContactList", OnSuccess = "successContactList", OnFailure = "failureContactList" }, new { groupid = item.Id })
</li>
}
</ul>
<div id="divContactList" >
#Html.Partial("ContactList", Model.SelectedGroup)
</div>
<div class="divContactList-bottom"> </div>
Is it possible to add sorting and searching functionality by AJAX or JavaScript?
Any help would be heartily appreciated.
Thank You.
While it's a different type of answer, I would have a look at jqGrid. It's a jquery plugin that will help you page, sort, and search through your tabular data.
http://www.trirand.com/blog/