using ajax loading search data to existing data grid - ajax

this is my action method
public ViewResult Index(string firstName)
{
// get the list of employees according to the user name
if (firstName == null)
{
return View((from e in db.Employees
where e.IsActive == true
select e).ToList());
}
else
{
return View((from e in db.Employees
where e.IsActive == true && e.FirstName.Contains(firstName )
select e).ToList());
}
}
This is my view
#{
var grid = new WebGrid(source: Model,
defaultSort: "UserName",
rowsPerPage: 15, ajaxUpdateContainerId: "grid");
}
#using (Html.BeginForm())
{
<div class="btn_align">
#if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Administrator"))
{
<h2>#Html.ActionLink("Create New", "Create")</h2>
}
</div>
<div class="btn_align">
<p>
Find by name:<input class="inputStyle_S" id="firstName" name="firstName" type="text" value="" data-autocomplete= "#Url.Action("QuickSearchFirstName", "ApplyLeave")" />
<input type="submit" id="txtSearch" value="Search" class="btn"/>
</p>
</div>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("User Name", format: (item) => item.FirstName + ' ' + item.LastName),
grid.Column("EmployeeType.Type", "Employee Type"),
grid.Column(header: "Action", format: (item) =>
Html.ActionLink("Details", "Details", new { id = item.id}))
)
)
</div>
}
</div>
<div class="leaveChart_bottom"></div>
I used web grid for representing data
I want get search results to exixting grid without refreshing page , after submiting search button (Search by name)
this is the ajax method I used ,but its not working.Can anyone helpme?

you should use #Ajax.BeginForm it will update your grid without refreshing the page. create a partial class for Grid so that you will get it's RenderHtmlString at server side.
In PartailClass
//GridPartail.cshtml
#model SomeModel
#{
var grid = new WebGrid(source: SomeModel,
defaultSort: "UserName",
rowsPerPage: 15, ajaxUpdateContainerId: "grid");
}
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("User Name", format: (item) => item.FirstName + ' ' + item.LastName),
grid.Column("EmployeeType.Type", "Employee Type"),
grid.Column(header: "Action", format: (item) =>
Html.ActionLink("Details", "Details", new { id = item.id}))
)
)
</div>
now modified your View
#using (#Ajax.BeginForm("Index", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "gridResult" }))
{
<div class="btn_align">
#if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Administrator"))
{
<h2>#Html.ActionLink("Create New", "Create")</h2>
}
</div>
<div class="btn_align">
<p>
Find by name:<input class="inputStyle_S" id="firstName" name="firstName" type="text" value="" data-autocomplete= "#Url.Action("QuickSearchFirstName", "ApplyLeave")" />
<input type="submit" id="txtSearch" value="Search" class="btn"/>
</p>
</div>
<div id="gridResult">
#html.Partail("GridPartail",Model)
</div>
}
NOTE: instead of using Html.BeginForm use Ajax.BeginForm.in your case you have not bind text box to model so that you will get it's value in formCollection
In Controller
[HttpPost]
public ActionResult Index(formCollection coll)
{
string firstName = coll["firstName"];
// get the list of employees according to the user name
if (firstName == null)
{
var result = from e in db.Employees
where e.IsActive == true
select e).ToList();
return PartailView("GridPartail",result );
}
else
{
//"GridPartail.cshtml" is partial viewName
var result = (from e in db.Employees
where e.IsActive == true && e.FirstName.Contains(firstName )
select e).ToList();
return View("GridPartail",result );
}
}
as in AjaxOption i have mention action method POST and you must be pass UpdateTargetId which specify where your result will appear on the view.

Related

How to pass data from View in Asp.NET MVC

i want to get the value of textbox for Controller
I used Ajax.ActionLink("Search","Result",new{id="**VALUE**"}, new AjaxOptions{...})
#* This is the Index.cshtml *#
<input id="cityName" type="text" class="form-control" placeholder="Enter a CityName">
#Ajax.ActionLink("Search", "Result", new { id = "I want to get the cityName" }, new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "cityInfo", LoadingElementId = "loading" }, new { #class = "btn btn-default" })
<div id="cityInfo"> #When I click the actionlink , the controller will return a partialview
#Html.Partial("Result", Model)
</div>
#*This is the Result.cshtml*#
<p>
#if (#Model!=null)
{
#Model.cityInfo
}
</p>
this is the index.cshtml ->>
enter image description here
Thanks
public PartialViewResult Result(string cityName)//this is the controller
{
CityModel city = new CityModel(cityName);
city.getInfo();
return PartialView("Index",city);
}
You can write a function like below:
Ajax.ActionLink("Search","Result",new{id="id"}, new AjaxOptions{...}) //set temp value
$(document).ready(function(){
//init value
var value = $('#cityName').val();
var href = $('a').attr('href').replace('id', value);
$('a').attr('href', href);
});

Button isn't sending to correct view

I am using ajax to send values to my controller from the view:
View where information is collected to send to a different controller:
#using (Html.BeginForm(null, null, FormMethod.Get, htmlAttributes: new { id = "GenerateForm" }))
{
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose AC:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("AC", null, "-- Select AC --", htmlAttributes: new { id = "AC", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Month:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Months", null, "-- Select Month --", htmlAttributes: new { id = "Month", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Year:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Years", null, "-- Select Year --", htmlAttributes: new { id = "Year", #class = "form-control" })
</div>
</div>
</div>
<br />
<input type="submit" id="SendToController" class="btn btn-primary" value="Generate" />
}
<script type="text/javascript">
$('#SendToController').on('click', function() {
sendToController();
return false;
});
function sendToController(){
var selectedAC = $('#AC').val();
var selectedMonth = $('#Month').val();
var chosenYear = $('#Year').val();
$.ajax({
url: '/MonthReports/Generate',
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){},
});
}
Controller Method:
public ActionResult Generate(int id, int monthValue, string year)
{
List<DailySum> lstDailySum = db.DailySum.Where(x => x.AID == id && x.Day.Month == monthValue + 1 && x.Day.Year.ToString() == year && x.deleted == false).ToList();
List<string> lstInc = lstDailySum.Select(x => x.codeAC.text).Distinct().ToList();
List<MReport> lstMReport = new List<MReport>();
foreach (var inc in lstInc)
{
MReport mReport = new MReport();
mReport.Inc = inc;
mReport.Count = lstDailySum.Where(x => x.codeAC.text == incident).Count();
lstMReport.Add(mReport);
}
return View(lstMReport);
}
Now the values are being passed through when the button is clicked, and the whole method works, except the View doesn't show up.. it just stays on the View where the button was originally clicked... no Generate View appears.
I have placed a breakpoint on the Generate view and it does get hit but the view doesn't show?
I don't know how else to explain it.. the cshtml code is hit with a breakpoint, but the page doesn't show.. it just stays on the page where the button was clicked.
Any help is appreciated.
Because you are using ajax, you should handle the data in the success callback of your ajax call. The way your code is written, you do nothing with the view. The View is rendered to the data variable.
Try something like this:
$.ajax({
url: '/MonthReports/Generate',
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){
$("body").html(data);
}
});

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
}

validation is not firing on textbox in RAZOR?

1below I have posted my total coding of view. Here validation is not firing on the textbox. I dont know how to sort out this problem. This view is executing. if I press the search textbox without entering the text in textbox, its not validating.Also tell me wheather I have to use TextBox or TextBoxFor. I am fresher and new to mvc3. Please tell me the solution.
#model IEnumerable< ShoppingCart.Models.ShoppingClass>
#{
ViewBag.Title = "Display";
}
<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>
#Html.ValidationSummary(true)
#using (Html.BeginForm("Display","Home", FormMethod.Post, new { id = "loginForm" }))
{
//for (int i = 0; i < 1; i++)
//{
<table><tr>o<td> #Html.Label("BrandName")</td>
<td>#Html.TextBox("BrandName") <div> #Html.ValidationMessage("BrandName")</div></td>
<td></td></tr></table>
#* <table><tr><td>
#Html.LabelFor(o=>o[i].BrandName)</td>
<td>#Html.EditorFor(o => o[i].BrandName) <div>#Html.ValidationMessageFor(o => o[i].BrandName)</div></td>
<td></td></tr></table>*#
// }
<input type="submit" value="Search" name="Search" />
}
#{
var grid = new WebGrid(source: Model, defaultSort: "Drug_Code", rowsPerPage: 20);
<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>
}
Edit: added a more complete example.
I'm not sure from the comments above if it's working to your satisfaction or not, but I think the root of your issue is that you are trying to use a model of IEnumerable where you don't need one. I understand that you need it for your grid, but what if you either put the grid or the search box in a PartialView? The PartialView could have its own model, and then you wouldn't need to fit your search box into a model that doesn't really fit.
The way I understand it, you're not actually passing data into the search box. You are only using the model at the search box so you get field validation. Let me know if that is incorrect.
Edit your view to look like this:
#model IEnumerable< ShoppingCart.Models.ShoppingClass>
#{
ViewBag.Title = "Display";
}
<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>
#Html.ValidationSummary(true)
#{Html.RenderPartial("_Search", Model.First());} //Need to make sure Model.First() actually exists, or you'll get error when it doesn't
//If you change your partial view to have a view model with just brand name, call it like this:
//#Html.RenderPartial("_Search", new _SearchViewModel())
//If you're only using the view model for required field validation on the return trip, then you don't actually need to pass data down to it.
#{
var grid = new WebGrid(source: Model, defaultSort: "Drug_Code", rowsPerPage: 20);
<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>
}
Create a Partial View (_Search):
#model ShoppingCart.Models.ShoppingClass
//You could also create a different View Model that just has brand name, and pass the data down another way
//See examples in the code for the view
#Html.ValidationSummary(true)
#using (Html.BeginForm("Display","Home", FormMethod.Post, new { id = "loginForm" }))
{
<table><tr><td>
#Html.LabelFor(o=>o.BrandName)</td>
<td>#Html.EditorFor(o => o.BrandName) <div>#Html.ValidationMessageFor(o => o.BrandName)</div></td>
<td></td></tr></table>
<input type="submit" value="Search" name="Search" />
}

ASP.NET MVC3: WebGrid + Ajax Filters + Ajax Sorting & Paging

Basically, I'm using WebGrid and I need to filter the results. The first problem I have here is it's my first time using WebGrid and I was hoping some of you could give me a hand with it... So far, I've managed to sort grid results and filter them with Ajax, but, when re-sorting the filtered results, the subset is lost and I go back to the beginning with the full set of results. I know why it's happening of course, but I don't figure out how to make it work.
Example:
On my view:
#model IQueryable<Cities>
#section MoreScripts
{
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
}
#using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "GridData"}))
{
<fieldset>
<legend>Search Filters</legend>
<br />
<div>
Name
</div>
<div>
#Html.TextBox("Name")
</div>
<p>
<input type="submit" value="Search" />
</p>
</fieldset>
}
<div id="GridData">
#Html.Partial("Grid", Model)
</div>
My Partial View:
#model IQueryable<Cities>
#{
var grid = new WebGrid<Cities>(null,rowsPerPage: 5, defaultSort: "Nombre", ajaxUpdateContainerId: "GridData");
grid.Bind(Model, autoSortAndPage: true, rowCount: Model.Count());
#grid.GetHtml(columns:
grid.Columns(
grid.Column("Name", "Name", canSort: true),
grid.Column("CreationDate", "Creation Date", canSort: true),
grid.Column("Active", "Active", canSort: true, format: #<text><input type="checkbox" disabled="disabled" value="#item.ID" #(item.Active == true ? "Checked" : null) /></text>),
grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { #class = "editLink smallCell", #title = "Edit" })),
grid.Column(format: (item) => Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { #class = "deleteLink smallCell", #title = "Delete" }))),
tableStyle: "webgrid",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style");
}
And finally what am doing wrong is here, on my controller:
public ActionResult Index()
{
return View(repository.GetAllRecords().OrderByDescending(f => f.CreationDate));
}
[HttpPost]
public ActionResult Index(string name)
{
var data = repository.GetAllRecords();
if(!string.IsNullOrEmpty(name))
data = data.Where(a => a.Name.Contains(name));
data = data.OrderByDescending(f => f.CreationDate);
return PartialView("Grid", data);
}
I'm also using a class WebGrid : WebGrid as seen here:
http://archive.msdn.microsoft.com/mag201107WebGrid/Release/ProjectReleases.aspx?ReleaseId=5667
So, this actually works fine for filtering, but once you get the filtered results and then try to change the sort order of your narrowed search results, you lose the elements and the 'name' parameter's value because the WebGrid goes agains the first controller action. Probably this is not the best approach, but as I said, I've never used WebGrid so I'm willing to learn. Any help would be really appreciated. Thanks.
Try to add FormMethod.Post to your form, so the request will go to the second ActionResult. Otherwise, the request is a GET, and goes to the first ActionResult Index() without the parameters.

Resources