How to sort partial view telerik grid? - c#

I' using telerik grid with mvc C#.
I create the telerik grid inside the partial view.My telerik grid sortiong is not working.
This is my Controller
public ActionResult Index()
{
var query = from c in db.tblCompanies
select c;
return View(query.ToList());
}
public ActionResult SearchCompany(string CompanyName)
{
var query = from c in db.tblCompanies
select c;
if (CompanyName != "")
{
query = query.Where(s => s.CompanyName.Contains(CompanyName));
}
return PartialView("_comList", query);
}
This is my view
script type="text/javascript">
function SearchCompany() {
var CompanyName = document.getElementById('txtCompanyName').value;
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("SearchCompany", "Company")',
data: ({ CompanyName: CompanyName }),
success: function (data) {
//alert(data);
$('#CompList').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
<table>
<tr>
<td>Company Name:</td>
<td>#Html.TextBox("txtCompanyName")</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Search" onclick="SearchCompany();" /></td>
</tr>
</table>
<div id="CompList">
#Html.Partial("_comList", CompanyList)
</div>
this is my partial view
#(Html.Telerik().Grid(Model)
.Name("CompanyGrid")
.Columns(columns =>
{
columns.Bound(o => o.CompanyId).Width(5).Title("ID"); ;
columns.Bound(o => o.CompanyName).Width(50);
columns.Bound(o => o.CompanyAddress).Width(60).Title("Address");
columns.Bound(o => o.Phone).Width(20);
columns.Bound(x => x.PKComID)
.Width(30)
.Template(x => Html.ActionLink("Edit", "Edit", new { id = x.PKComID }))
.ClientTemplate(" EDIT ")
.Title("Edit").Sortable(false);
columns.Bound(x => x.PKComID)
.Width(30)
.Template(x => Html.ActionLink("Delete", "Delete", new { id = x.PKComID }, new { onclick = "return confirm('Are you sure you wish to delete this Company?');" }))
.ClientTemplate(" EDIT ")
.Title("Delete").Sortable(false);
})
.Pageable(paging => paging.PageSize(15).Style(GridPagerStyles.NextPreviousAndNumeric).Position(GridPagerPosition.Bottom))
.Sortable()
)
what is the wrong with my code.. sorting is not working
please help me.

Make sure that you have correctly implemented all steps from the Telerik ASP.NET MVC - Grid - Sorting demo.

Related

how to implement autocomplete functionality in search box in .net core mvc?

I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works. I followed different tutorials but not able to solve it. Please take a look and give me the direction.
Thnx in advance.
Controller
public async Task<IActionResult> dashboard(string sortOrder, string SearchString)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(SearchString))
{
movies = movies.Where(s => s.MovieName.Contains(SearchString));
}
switch (sortOrder)
{
case "name_desc":
movies = movies.OrderByDescending(s => s.MovieName);
break;
default:
movies = movies.OrderBy(s => s.MovieName);
break;
}
return View(await movies.AsNoTracking().ToListAsync());
}
public JsonResult AutoComplete(string prefix)
{
var customers = (from movie in this._context.Movie
where movie.MovieName.StartsWith(prefix)
select new
{
label = movie.MovieName,
val = movie.Id
}).ToList();
return Json(customers);
}
dashboard.cshtml
#model IEnumerable<WebApplication1.Models.Movie>
#{
ViewData["Title"] = "dashboard";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Dashboard</h1>
#using (Html.BeginForm())
{
<p>
Find by Movie Name: #Html.TextBox("SearchString")
<input type="hidden" id="hfCustomer" name="Id" />
<input type="submit" value="Search" />
</p>
}
<table class="table">
<thead>
<tr>
<th>
<a asp-action="dashboard" asp-route-sortOrder="#ViewData["NameSortParm"]">#Html.DisplayNameFor(model => model.MovieName)</a>
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.MovieName)
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(function () {
$("#txtMovie").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Movies/AutoComplete/',
data: { "prefix": request.term },
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works.
Find by Movie Name: #Html.TextBox("SearchString")
If you check the html source code of above TextBox in your browser, you would find it is rendered as below.
The value of id attribute is "SearchString", not "txtMovie". You can try to modify the code to use $("#SearchString") selector, like below.
$("#SearchString").autocomplete({
//...
//code logic here
//...
Test result with testing data
Note: please make sure you add references to required jquery libraries.
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

What is the most likely cause of the 500 error here?

I will show you all the moving parts involved.
View:
#{
ViewBag.Title = "Partners";
}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h1>Partners</h1>
<p>Click to see survey answers or delete partner</p>
<table class="table">
<thead>
<tr>
<th>Partner Name</th><th>Actions</th>
</tr>
</thead>
<tbody>
#foreach ( var NameIdPair in ViewBag.PartnersAndIds )
{
<tr>
<td>
#NameIdPair.Name
</td>
<td>
<button class="btn btn-info view-partner-surveys" data-partnerid="#NameIdPair.Id">View Survey Answers</button>
<button class="btn btn-warning delete-partner" data-partnerid="#NameIdPair.Id">Delete Partner</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#section bottommost {
<script type="text/javascript">
$('.delete-partner').click(function () {
var row = $(this).closest('tr');
$.ajax({
method: 'POST',
url: 'DeletePartner',
data: { pid: $(this).attr('data-partnerid') },
dataType: 'json',
processData: false,
beforeSend: function () {
row.addClass('processing');
},
success: function (retinfo) {
if (retinfo.DeletedSuccessfully) { row.remove(); }
else { alert("Error .."); row.removeClass('processing'); }
},
error: function () { alert("Error"); row.removeClass('processing'); }
});
});
</script>
}
The problem is occuring with the AJAX call invoked with $('.delete-partner').click. The controller handling the request is the simple
[HttpPost]
public ActionResult DeletePartner ( int pid )
{
return Json(new { DeletedSuccessfully = this._Db.DeletePartner(pid) });
}
which used the method DeletePartner in a model defined by
public bool DeletePartner ( int id )
{
SqlCommand cmd = new SqlCommand("DeletePartner", this._Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
this._Conn.Open();
bool succeeded = cmd.ExecuteNonQuery() == 1 ? true : false;
this._Conn.Close();
return succeeded;
}
The sproc its calling is the simple
CREATE PROCEDURE DeletePartner
#id INT
AS
DELETE FROM Partners WHERE id=#id
Any idea where I'm going wrong here?
You should use the url of your ajax call like following.
url: '#Url.Action("DeletePartner")'
You have to give ajax url in the format like
url : '../controllerName/ActionName'
[HttpPost]
public ActionResult DeletePartner ( int pid )
{
return Json(new { DeletedSuccessfully = this._Db.DeletePartner(pid) });
}
The DeletedSuccessfully variable is not recognised by the controller. So it may cause 500 error

Table with combobox on one of fild data-binding

I need create table with field with combobox on page. But I can't bind valid items to combobox, all combobox have default values - 'Please Select...'. Can you help me?
My html code fragment:
<td><label data-bind="text: name"></label></td>
<td><label data-bind="text: description"></label></td>`enter code here`
<td>
<select class="controls contol-width span2" id="cmbSelectedInfo" required="required" data-bind="
options: vm.infoes,
value: vm.selectedInfoID,
optionsText:'code',
optionsValue: 'infoID',
optionsCaption: 'Please Select...'"></select>
</td>
My viewmodel in typescript:
class MyViewModel {
infoes: KnockoutObservableArray<any>;
selectedInfoID: KnockoutObservable<number>;
constructor() {
this.infoes = ko.observableArray();
this.selectedInfoID = ko.observable<number>();
}
getInfoes(url: string, onError: (message: string) => {}) {
(<any>this).getJson(url, (data: any) => {
<any>this.infoes((<any>ko).mapping.fromJS(data).infoes());
} ,(message: string) => {
onError(message);
});
}
getJson(url: string, onSuccessed: (data: any) => {}, onError: (message: string) => {}) {
var self = this;
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: (data) => {
if (data.succeeded) {
onSuccessed(data);
} else {
onError((<any>data).error);
}
},
error: (data) => {
onError((<any>data).error);
}
});
}

Pass ID in Html.ActionLink via ajax to get partial view

I have an MVC View page, strongly-typed to an enumerated product list. Each list item has an Html.ActionLink with a unique id. In my jquery file, I have an $.ajax function which should process the link with the corresponding id . The intent is to load a partial view on the same page, with that item's information, to allow editing for whatever item has been clicked. I don't want the actionr to result in a separate page, or generate a post to the server.
// here is the MVC stuff
#model IEnumerable<SimpleAjax.Models.Product>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { id = "btnShowEdit" + item.Id, #class= ".button_action"})
|
</td>
</tr>
}
<div id="showEditProd">
</div>
//inside controller
public ActionResult ShowEdit(int id)
{
Product prod = db.Product.Find(id);
ProductViewModel viewModel = new ProductViewModel
{
EditProduct = prod
};
return PartialView(viewModel);
}
//inside a separate partial view page
#model SimpleAjax.Models.ProductViewModel
#using (Html.BeginForm("Index_AddItem", "Home", FormMethod.Post, new { id = "fid" }))
{
<div>
#Html.LabelFor(model => model.EditProduct.Name)
#Html.EditorFor(model => model.EditProduct.Name)
</div>
<div>
#Html.LabelFor(model => model.EditProduct.Price)
#Html.EditorFor(model => model.EditProduct.Price)
</div>
<div>
<input type="submit" value="Submit" />
</div>
}
now below works as expected, when I have hardcoded IDs:
$('#btnShowEdit1,#btnShowEdit2,#btnShowEdit3').click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
The above jquery works as desired. The partial view gets loaded on the same page as enumerated list. But obviously I don't want to hardcode variables. I may have x number of #btnShowEdit. I want to utilize a class, correct? So I have ".button_action" class that will enumerate the Id. But when I do that, as below, the link navigates to a separate page.
these go to a separate page, not what I want
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
//also tried this...
$('.button_action').each(function (index) {
$('#btnShowEdit' + index).click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
I know there's gotta be a simple solution.Thanks for your help in advance.
Any specific reason for not using the Ajax HTML-helper?
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.actionlink(v=vs.108).aspx
You can use it as an actionlink, but it is done async and the result can be placed in your showEditProd.
#Ajax.ActionLink("Action",
"Controller",
_YOURID_,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "showEditProd",
OnComplete = "your_js_function();" })
In case anyone else needs the solution to the above... It was too simple to believe.The jquery ajax code does not need an id htmlattribute from the Html.ActionLink. In fact, this extra attribute is what was causing the trouble. The jquery ajax recognizes the id from the "this.href' as that is the route controller along with the id parameter. Therefore I removed the id from htmlattributes in the actionlink. Now it's working as expected.
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { #class= ".button_action"})
in js file
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
Check this:
$('.button_action').click(function (e) {
e.preventDefault() // this prevent default behavior for hyperlink on 'click' event

Jquery Post not reaching MVC Controller

Apologies if this i trivial, i have read many other comments and still cannot see what is wrong. I have done a few tutorials and they seem to work ok, so I am really missing something simple.
I have a basic 'remove' link that i want to do a JQuery Post back to the controller to remove an item from the database and then update the view.
My View / Javascript:
<script type="text/javascript">
$(function () {
$(".RemoveLink").click(function () {
var id = $(this).attr("data-id");
if (id != '') {
$.post("#Url.Content("~/Agent/Remove")", { "id": id }, function (data) { alert('Here i am'); });
}
});
});
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.ID" >Remove</a>
</td>
</tr>
}
My Controller:
[HttpPost]
public ActionResult Remove(int id)
{
return Json(new { Data = "true" });
}
Any assistance will be great.
Use #Url.Action("Remove", "Agent") instead.
#Url.Content("...") is used to locate any static content of the site.
Cheers
Below code works well.
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<input type="button" class="RemoveLink" id="#item.ID" Value="Remove" />
</td>
</tr>
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('.RemoveLink').live("click", function () {
Remove($(this));
});
});
function Remove(_this) {
var Id= $(_this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("Remove", "Agent")',
data: "{id: '" + Id + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
//do something here......
},
error: function () {
}
});
}
</script>

Categories