How to filtering gridview in MVC3? - asp.net-mvc-3

I have gridview in Data and dropdownlist data whenever i select the Resourcename only filter that name ..........
how to write code in controller?
My contollercode
public List<BugTracker_DataHelper> GeGridView()
{
var modelList = new List<BugTracker_DataHelper>();
using (SqlConnection conn = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MvcBugTracker;Data Source=SSDEV6\SQLEXPRESS"))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("Select * from Resources", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new BugTracker_DataHelper();
model.ResourceID = Convert.ToInt16(ds.Tables[0].Rows[i]["ResourceID"]);
model.ResourceName = ds.Tables[0].Rows[i]["ResourceName"].ToString();
model.EmployeEmailID = ds.Tables[0].Rows[i]["EmailID"].ToString();
//model.status = ds.Tables[0].Rows[i]["Status"].ToString();
modelList.Add(model);
}
}
return modelList;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Grids(FormCollection collection,string ResourceName,int ResourceId)
{
return View();
}
My ModelCode
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Gridview_BugTracker.Models.BugTracker_DataHelper>>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<link href="../../Content/GridStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Grids</title>
</head>
<body>
<div>
<%: Html.DropDownList("ResourceID", (SelectList)ViewBag.ResourceID, "--Select Project--")%>
<%: Html.ValidationMessage("ResourceID")%>
<%: Html.DropDownList("ResourceName", (SelectList)ViewBag.ResourceName, "--Select Project--")%>
<%: Html.ValidationMessage("ResourceName")%>
<%
var grid = new WebGrid(source: Model, defaultSort: "ResourceName", rowsPerPage: 3);
using (Html.BeginForm())
{ %>
<div id="grid">
<%:grid.GetHtml(
tableStyle: "listing-border", headerStyle: "gridhead", footerStyle: "paging", rowStyle: "td-dark", alternatingRowStyle: "td-light",
columns:grid.Columns(
grid.Column("ResourceID"),
grid.Column("ResourceName"),
grid.Column("EmployeEmailID"),
grid.Column(
header: "",
style: "text-align-center",
format: (item) => Html.ActionLink("Edit", "Edit", new { ResourceID = item.ResourceID }))
))%>
</div>
<%} %>
</div>
</body>
</html>
how write in controller code..
please can any one help me

Related

does not contain public definition for get enumerator

my view statement shows error that " for each statement cannot operate on variables of type public definition for 'get enumerator' "
I defined all objects in model and view models. still i get this error. any solution for this?
MY VIEW:
#using Edi.ViewModel
#model viewmodel
#{
<link rel="stylesheet" type="text/css" href="~/Content/style.css" />
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form id="form1" name="zoo">
<div class="med">
<pre>
<fieldset id="field1">
<legend>Bill Date Range</legend>
<input type="checkbox">After <input type="date" /> <input type="checkbox">Before <input type="date" />
</fieldset>
<fieldset id="field2">
<legend>Options</legend>
<label>Facility</label> #Html.DropDownListFor(Model => Model.Facility, Model.Facility, "Select Facility", new { style = "width:200px; height :30px" })
<label>Ins Queue</label> #Html.DropDownListFor(Model => Model.InsQueue, Model.InsQueue, "Select InsQueue", new { style = "width:200px; height:30px" })
Claim type <select style="width: 100px; height:30px"><option value="ALL">All</option><option value="NEW">New</option><option value="RESUBMIT">Resubmit</option></select>
</fieldset>
<pre>
<label>No of Bills Selected </label><input type="text" size="1" /> <label> EDI send To </label> #Html.DropDownListFor(Model => Model.EdiSendTo, Model.EdiSendTo, "Select Edi", new { style = "width:200px; height :30px" }) <button type="button" onclick="">Select All</button> <button type="reset" onclick="">Refresh</button> <button type="button" onclick="">Clear All</button> <button type="button" onclick="">Edit Bill</button>
</pre>
<table id="myTable">
<tr class="hd">
<th>visit</th>
<th>billno</th>
<th>patient</th>
<th>providername</th>
<th>insname</th>
<th>payby</th>
<th>inscode</th>
<th>user</th>
<th>claimtype</th>
</tr>
-------------------#foreach (var items in Model)------------------------------
{
<tr onclick="javascript:showRow1(this);">
<td>#items.visit</td>
<td>#items.billno</td>
<td>#items.Patient</td>
<td>#items.ProviderName</td>
<td>#items.InsName</td>
<td>#items.PayBy</td>
<td>#items.InsCode</td>
<td>#items.User</td>
<td>#items.ClaimType</td>
</tr>
}
</table>
</div>
</form>
</body>
</html>
MY CONTROLLER:
namespace Edi.Controllers
{
public class HomeController :Controller
{
// GET: Home
public ActionResult Index()
{
mbill mt = new mbill();
billing db = new billing();
viewmodel vm = new viewmodel();
vm.Facility = db.Add1();
vm.EdiSendTo = db.Add2();
vm.InsQueue = db.Add3();
List<mbill> itemlist = new List<mbill>();
itemlist = db.Index();
return View("Index",vm);
}
}
}
MY MODEL:
public List<mbill> Index()
{
List<mbill> itemList = new List<mbill>();
connection();
SqlCommand cmd = new SqlCommand("procGetEDIBills", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
mbill item = new mbill();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
mbill io = new mbill();
while (sdr.Read())
{
io = new mbill();
io.visit = sdr["VisitDate"].ToString();
io.billno = sdr["Billno"].ToString();
io.Patient = sdr["PatientName"].ToString();
io.ProviderName = sdr["ProviderName"].ToString();
io.InsName = sdr["InsuranceName"].ToString();
io.PayBy = sdr["BillPayBy"].ToString();
io.InsCode = sdr["InsuranceId"].ToString();
io.User = sdr["QueueByUser"].ToString();
io.ClaimType = sdr["ClaimType"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
if i delete #using Edi.ViewModel, #model viewmodel, on view then foreach error disappears and dropdownlistfor shows does not contain definition for dropdownlistfor error.

asp.net mvc + Ajax.BeginForm OnBegin not firing

After reading several posts regarding this issue, it is mostly related to including
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
and the proper order of including jquery first.
<script src="~/Scripts/jquery-1.12.4.js"></script>
I think I did properly, but OnBegin is not firing still.
_Layout.cshtml:
<head>
<meta charset="utf-8" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<title>Test</title>
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/respond.min.js"></script>
<script src="~/Scripts/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.colVis.min.js"></script>
<script src="~/Scripts/light-bootstrap-dashboard.js"></script>
<script src="~/Scripts/bootstrap-notify.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#RenderSection("scripts", required: false)
</head>
So the order of process is:
School View:
#model Test.Models.School
<div class="editorRow">
#using (Html.BeginCollectionItem("schools"))
{
#Html.ActionLink("New Employee", "NewEmployee", "Test", new
{
#class = "btn btn-info btn-md",
data_toggle = "modal",
data_target = "#modal-container-employee"
})
</div>
<div id="modal-container-employee" class="modal fade" tableindex="-1" role="dialog">
<div class="modal-content">
<div class="modal-body">
</div>
</div>
</div>
Controller:
public ActionResult NewEmployee()
{
var newEmployee = new Employee();
return View(newEmployee);
}
Employee view:
#model Test.Models.Employee
#{
Layout = null;
}
#using (Ajax.BeginForm("PostEmployee", "Employee", new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
OnBegin = "closeModal"
}))
{
#Html.AntiForgeryToken()
<div id="test" class="">
<div class="modal-title title">
<input type="submit" id="submit" value="Save" /><span id="closes">x</span>
</div>
#Html.EditorFor(model => model.FullName)
</div>
}
<script>
function closeModal() {
$('#modal-container').modal('hide');
}
</script>
controller:
[HttpPost]
public ActionResult PostEmployee(Employee model)
{
try
{
var newEmployee = new Employee
{
FullName = model.FullName
};
db.Employees.Add(newEmployee);
db.SaveChanges();
return Json(new { status = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { status = "error", errorMessage = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
As a result, "success" Json is returned, but ajax is not catching it, it directly goes to the other page where it shows JSON array {"status":"success"}.
Can anyone find the problem?

Jquery DataTable in MVC JsonResult

I'm new in web and trying to draw JQuery.DataTable. This is my action:
public ActionResult Index(jQueryDataTableParamModel param)
{
var result = new List<Company>()
{
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
};
return Json(new{
sEcho = param.sEcho,
iTotalRecords = result.Count(),
iTotalDisplayRecords = result.Count(),
aaData = result
}, JsonRequestBehavior.AllowGet);
}
}
And this is my View:
#model IEnumerable<TestProject.Models.Company>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
<link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/dataTables.bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/DataTables/dataTables.bootstrap.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<title>Index</title>
</head>
<body>
<div>
<table id="myDataTable">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr id="#item.ID">
<td>#item.Name</td>
<td>#item.Address</td>
<td>#item.Town</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "JQueryTableTestController/Index",
"bProcessing": true,
"aoColumns": [
{ mDataProp: "Name", sTitle: "Company Name" },
{ mDataProp: "Address", sTitle: "Address" },
{ mDataProp: "Town", sTitle: "Town" }
]
});
});
</script>
And I can't understand what am I doing wrong. I'm trying do this reading the article: http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
Without Json result all works fine. But I wanna to do this using Json, because I want to do server side paging, filtering, sorting. Can anyone tell me: what I'm doing wrong?

How to hide the webgrid when execute the page in mvc3 razor?

When I remove the webgrid and layout=null in the view, its executing and client side validation message is displaying... but When I execute the page with layout= nlll and Webgrid it displaying the below error "A data source must be bound before this operation can be performed"
Controller :
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Display()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Display(string brandname)
{
ShoppingClass s = new ShoppingClass();
var ob= s.Searching(brandname);
return View(ob);
}
view :
#model List<ShoppingCart.Models.ShoppingClass>
#{
ViewBag.Title = "Display";
Layout = null;
}
#{
var grid = new WebGrid(source: Model, defaultSort: "Drug_Code", rowsPerPage: 20);
}
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#using (Html.BeginForm(null, null, FormMethod.Post))
{
for (int i = 0; i < 1; i++)
{
#*
<table><tr><td> #Html.Label("BrandName")</td>
<td>#Html.TextBox("BrandName")<div>#Html.ValidationMessage("BrandName")</div></td>
<td><input type="submit" value="Search" name="Search" /></td></tr></table>*#
<table><tr><td> #Html.LabelFor(o => o[i].BrandName)</td>
<td>#Html.TextBoxFor(o => o[i].BrandName)<div>#Html.ValidationMessageFor(o => o[i].BrandName)</div></td>
<td><input type="submit" value="Search" name="Search" /></td></tr></table>
}
}
<div id="grid">
#grid.GetHtml(tableStyle: "listing-border", headerStyle: "gridhead", footerStyle: "paging", rowStyle: "td-dark", alternatingRowStyle: "td-light",
columns: grid.Columns(
grid.Column("GenericName", format: #<text>#item.GenericName</text>),
grid.Column("BrandName", format: #<text>#item.BrandName</text>),
grid.Column("Purchaseqty", format: #<text>#item.Purchaseqty</text>),
grid.Column("Purchaseprice", format: #<text>#item.Purchaseprice</text>),
grid.Column("Drug_Code", format: #<text>#item.Drug_Code</text>),
grid.Column(header: "", format: (item) => Ajax.ActionLink("Add to Cart", "ADDTOCART",
new { brandname = #item.BrandName, purchaseqty = #item.Purchaseqty, drugcode = #item.Drug_Code }, new AjaxOptions { HttpMethod = "Post", OnSuccess = "ADDTOCART" }))
)
)
</div>
If you want to hide the grid if the model is null, then you can put an if statement in that checks if the model is null... ie.
if (model != null)
{
// Make and populate grid here
}

MVC3 Ajax.BeginForm with javascript disabled

I'm having a problem getting a form to work without javascript being enabled.
This should be enough to go on, ask if you need to know anything else - I don't want to just put the whole solution up here!
~/Views/_ViewStart.cshtml:
#{ Layout = "~/Views/Shared/Layout.cshtml"; }
~/Views/Shared/Layout.cshtml:
#using System.Globalization; #{ CultureInfo culture = CultureInfo.GetCultureInfo(UICulture); }<!DOCTYPE html>
<html lang="#culture.Name" dir="#(culture.TextInfo.IsRightToLeft ? "rtl" : "ltr")">
<head>
<title>AppName :: #ViewBag.Title</title>
<link href="#Url.Content("~/favicon.ico")" rel="shortcut icon" type="image/x-icon" />
<link href="#Url.Content("~/apple-touch-icon.png")" rel="apple-touch-icon" />
<link href="#Url.Content("~/Content/css/site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Content/js/jquery-1.6.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/app.js")" type="text/javascript"></script>
#RenderSection("SectionHead", false)
</head>
<body>
<div id="page-container">
<div id="nav">
<div id="nav-user">
#{ Html.RenderAction("LoginStatus", "Account"); }
#{ Html.RenderPartial("CultureSelector"); }
</div>
</div>
<div id="page-content">
<h2>#ViewBag.Title</h2>
#RenderBody()
</div>
</div>
</body>
</html>
~/Views/Account/Index.cshtml:
#model AccountFilterModel
#{
ViewBag.Title = "Account Home";
var loadingId = "loading" + new Random().Next();
Model.FilterFormId = "filter-account-form";
}
#using (Ajax.BeginForm("List", "Account", Model, new AjaxOptions { UpdateTargetId = "result-list", LoadingElementId = loadingId }, new { id = "filter-account-form" })) {
<!-- form controls and validation summary stuff -->
<input id="filter" type="submit" value="Filter" />
<span id="#loadingId" style="display: none">
<img src="#Url.Content("~/Content/images/ajax-loader.gif")" alt="Loading..." />
</span>
}
<div id="result-list">
#{ Html.RenderAction("List", Model); }
</div>
~/Views/Account/List.cshtml:
#model FilterResultModel
#helper SortLink(AccountSort sort, SortDirection dir) {
string display = (dir == SortDirection.Ascending ? "a" : "d"); // TODO: css here
if (Model.Filter.SortBy != null && ((AccountSortModel)Model.Filter.SortBy).Sort == sort && dir == Model.Filter.SortOrder) {
#:#display
} else {
FilterModel fm = new FilterModel(Model.Filter);
fm.SortBy = AccountSortModel.SortOption[sort];
fm.SortOrder = dir;
#display
}
}
#if (Model.Results.Count > 0) {
var first = Model.Results.First();
<table>
<caption>
#string.Format(LocalText.FilterStats, Model.FirstResultIndex + 1, Model.LastResultIndex + 1, Model.CurrentPageIndex + 1, Model.LastPageIndex + 1, Model.FilteredCount, Model.TotalCount)
</caption>
<thead>
<tr>
<th>
#Html.LabelFor(m => first.Username)
<span class="sort-ascending">
#SortLink(AccountSort.UsernameLower, SortDirection.Ascending)
</span>
<span class="sort-descending">
#SortLink(AccountSort.UsernameLower, SortDirection.Descending)
</span>
</th>
<!-- other table headers -->
</tr>
</thead>
<tbody>
#foreach (AccountModel account in Model.Results) {
<tr>
<td>#Html.EncodedReplace(account.Username, Model.Filter.Search, "<span class=\"filter-match\">{0}</span>")</td>
<!-- other columns -->
</tr>
}
</tbody>
</table>
Html.RenderPartial("ListPager", Model);
} else {
<p>No Results</p>
}
Relevant part of AccountController.cs:
public ActionResult Index(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return View(fm);
}
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
With javascript enabled, this works fine - the content of div#result-list is updated as expected.
If I don't do the Request.AjaxRequest() and just return the PartialView, then with javascript disabled I get a page with just the content of the results on it. If I have the code as above, then I get a StackOverflowException.
How do I get this to work?
Solution
Thanks to #xixonia, I discovered the problem - here is my solution:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue)
fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
if (Request.HttpMethod == "GET")
return PartialView("List", Service.Get(fm));
if (Request.HttpMethod == "POST")
return Request.IsAjaxRequest() ? (ActionResult) PartialView("List", Service.Get(fm)) : RedirectToAction("Index", model);
return new HttpStatusCodeResult((int) HttpStatusCode.MethodNotAllowed);
}
You can use the following extension method to determine if the request is an ajax request
Request.IsAjaxRequest()
If it is, you can return a partial view, otherwise you can return a full view or redirect.
if(Request.IsAjaxRequest())
{
return PartialView("view", model);
}
else
{
return View(model);
}
edit: here's the problem:
The "List" is returning the "Index" view when the request is not an AJAX request:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
The "Index" view is rendering the "List" action:
#{ Html.RenderAction("List", Model); }
AKA: Recursion.
You need to engineer a way to display your list without drawing the index page, or make your index page draw a partial view with your list modal as a parameter.

Resources