I write a web in mvc framework with angular js.
my application is:
var app = angular.module("AngularApp", []);
and my controller is:
app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();
function GetAllEmployee() {
var getAllEmployee = EmployeeService.getEmployee();
getAllEmployee.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('data not found');
});
}
$scope.deleteEmployee = function (id) {
var getData = EmployeeService.DeleteEmp(id);
getData.then(function (msg) {
GetAllEmployee();
alert('Employee Deleted...');
$scope.h1message = true;
$scope.message = "ED";
}, function () {
$scope.h1message = true;
$scope.message = "Error in Deleting Record";
});
}
});
and my service is:
app.service("EmployeeService", function ($http) {
this.getEmployee = function () {
debugger;
return $http.get("/EmployeeModels/GetAllEmployee");
};
//Delete Employee
this.DeleteEmp = function (employeeId) {
var response = $http({
method: "post",
url: "/EmployeeModels/deleteEmployee",
params: {
employeeId: JSON.stringify(employeeId)
}
});
return response;
}
});
and my mvc action is :
private ApplicationDbContext db = new ApplicationDbContext();
public JsonResult GetAllEmployee()
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
var employeeList = db.EmployeeModels.ToList();
return Json(employeeList, JsonRequestBehavior.AllowGet);
}
}
//DeleteEmployee
public string DeleteEmployee(string employeeId)
{
if (employeeId != null)
{
int no = Convert.ToInt32(employeeId);
var employeeList = db.EmployeeModels.Find(no);
db.EmployeeModels.Remove(employeeList);
db.SaveChanges();
return "Employee Deleted";
}
else { return "Invalid Employee"; }
}
and html file is:
<div ng-app="AngularApp" ng-init="name='hn';backGroundColor='red';
person={firstname:'jo',lastname:'hary'}">
<div ng-controller="EmpCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('emp.EmployeeId')">employee id</th>
<th ng-click="orderByMe('Address')">addres</th>
<th ng-click="orderByMe('EmailId')">email id</th>
<th ng-click="orderByMe('EmployeeName')">employee name</th>
</tr>
<tr ng-repeat="emp in employees|orderBy:orderByMe">
<td> {{emp.EmployeeId}}</td>
<td> {{emp.Address}}</td>
<td>{{emp.EmailId}}</td>
<td>{{emp.EmployeeName}}</td>
<td><a data-ng-click="deleteEmployee(emp.EmployeeId)" style="cursor:pointer;">delete</a></td>
</tr>
</table>
</div>
the view of data is ok. but when I add record to table of database, view not refresh data?
Your view not refresh data because, your method GetAllEmployee() is called once, at the loading of page. you need to refresh your page.
Related
I need to create a datatable that only displays records that have only one Activity Phase equal to "Waiting". Currently, the following solution displays all records, some of which have multiple Activity Phases. The first Activity Phase in the workflow is "Waiting".
Actions:
public JsonResult LoadWaitList()
{
return Json(new { data = GetWaitList() }, JsonRequestBehavior.AllowGet);
}
private IEnumerable GetWaitList()
{
var waitList = from a in _db.Applications
select new
{
a.AppNumber, ApplicationType = a.ApplicationType.Label,
ActivityPhases = a.ApplicationActivityPhas.Select(p => p.ActivityPhas.ActivityPhase).ToList(),
a.Id
};
return waitList;
}
DataTable:
$("#WaitListDataTable").DataTable({
ajax: {
url: '#Url.Action("LoadWaitList", "Application")',
datatype: "json",
type: "GET"
},
columns: [
{
data: "AppNumber",
render: function (data, type, row) {
var applicationDetails = '#Url.Action("Details", "Application")/' + row.Id;
return '' + data + '';
}
},
{ data: "ApplicationType" },
{ data: "ActivityPhases" },
{ data: "Id" }
]
});
Index Table:
<div class="pt-2">
<table class="table table-bordered table-sm" id="WaitListDataTable">
<thead class="table-info">
<tr>
<th>Application Number</th>
<th>Application Type</th>
<th>Activity Phase</th>
<th>Id</th>
</tr>
</thead>
</table>
</div>
Since "Waiting" is the first activity phase in the workflow, to display application records that only have one activity phase equal to "Waiting", I added the following:
public JsonResult LoadWaitList()
{
return Json(new { data = GetWaitList() }, JsonRequestBehavior.AllowGet);
}
private IEnumerable GetWaitList()
{
var waitList = (from a in _db.Applications
select new
{
a.AppNumber, ApplicationType = a.ApplicationType.Label,
ActivityPhases = a.ApplicationActivityPhas.Select(p => p.ActivityPhas.ActivityPhase).ToList(),
a.Id
}).Where(p => p.ActivityPhases.Count() == 1);
return waitList;
}
I am trying to implement ASP.NET MVC Paging using MVC4.Paging nuget package.
Problem:
It is working in online demo and also in the download source code. However I am not able to find why it is not working in my particular project by AJAX. In my project it is working by full post back method but not Ajax.
I have even tried to copy over the Index action method and Index and _AjaxEmployeeList Views (.cshtml) files (except .js).
Note: In my solution its not bootstrap as shown in samples. Also my controller name is AdminController whereas in Samples its HomeController
In my solution I need it to work in AJAX method as in samples.
Kindly help regarding:
1. How to find the root cause for why it is not working?
2. How to make this working?
.
My Solution Code (which I tried to reproduce in my solution from the sample):
Index.cshtml
#using MvcPaging
#model IPagedList<MvcPagingDemo.Models.Employee>
#{
ViewBag.Title = "MVC 4 Paging With Ajax Bootstrap";
}
<div class="row-fluid">
<div class="span6">
<h2>
Ajax Paging With Bootstrap In MVC 4
</h2>
</div>
<div class="span6">
<div class="alert alert-info">
The pager also supports area's. #Html.ActionLink("Ajax paging in an area", "Index", "Admin", new { Area = "AreaOne" }, new { #class = "btn btn-success" })</div>
</div>
</div>
<div class="clearfix">
</div>
#using (Ajax.BeginForm("Index", "Admin",
new AjaxOptions { UpdateTargetId = "grid-list", HttpMethod = "get", LoadingElementId = "loading", OnBegin = "beginPaging", OnSuccess = "successPaging", OnFailure = "failurePaging" },
new { id = "frm-search" }))
{
<div class="input-append">
<input class="span2" id="appendedInputButton" type="text" name="employee_name" placeholder="Name" />
<button class="btn" type="submit">
<i class="icon-search"></i> Search</button>
</div>
<div id="grid-list">
#{ Html.RenderPartial("_AjaxEmployeeList", Model); }
</div>
}
<script type="text/javascript">
function beginPaging(args) {
// Animate
$('#grid-list').fadeOut('normal');
}
function successPaging() {
// Animate
$('#grid-list').fadeIn('normal');
$('a').tooltip();
}
function failurePaging() {
alert("Could not retrieve list.");
}
</script>
_AjaxEmployeeList.cshtml
#using MvcPaging
#model IPagedList<MvcPagingDemo.Models.Employee>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Email
</th>
<th>
Phone
</th>
<th>
City
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.ID
</td>
<td>
#item.Name
</td>
<td>
#item.Email
</td>
<td>
#item.Phone
</td>
<td>
#item.City
</td>
</tr>
}
</tbody>
</table>
<div class="pager1">
#Html.Raw(Ajax.Pager(
new Options
{
PageSize = Model.PageSize,
TotalItemCount = Model.TotalItemCount,
CurrentPage = Model.PageNumber,
ItemTexts = new ItemTexts() { Next = "Next", Previous = "Previous", Page = "P" },
ItemIcon = new ItemIcon() { First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward" },
TooltipTitles = new TooltipTitles() { Next = "Next page", Previous = "Previous page", Page = "Page {0}." },
Size = Size.normal,
Alignment = Alignment.centered,
IsShowControls = true,
IsShowFirstLast = true,
CssClass = ""
},
new AjaxOptions
{
UpdateTargetId = "grid-list",
OnBegin = "beginPaging",
OnSuccess = "successPaging",
OnFailure = "failurePaging"
}, new { controller = "Admin", action = "Index", employee_name = ViewData["employee_name"] }))
<div class="well">
Showing <span class="badge badge-success">#Model.ItemStart</span> to <span class="badge badge-success">#Model.ItemEnd</span>
of <span class="badge badge-info">#Model.TotalItemCount</span> entries</div>
</div>
AdminController.cs
public class AdminController : Controller
{
private const int defaultPageSize = 3;
private IList<Employee> allEmployee = new List<Employee>();
private string[] name = new string[4] { "Will", "Johnny", "Zia", "Bhaumik" };
private string[] phone = new string[4] { "1-274-748-2630", "1-762-805-1019", "1-920-437-3485", "1-562-653-8258" };
private string[] email = new string[4] { "donec#congueelitsed.org", "neque.non#Praesent.co.uk", "et.magna#Pellentesque.ca", "enim.commodo#orci.net" };
private string[] city = new string[4] { "Wigtown", "Malderen", "Las Vegas", "Talence" };
public AdminController()
{
InitializeEmployee();
}
private void InitializeEmployee()
{
// Create a list of 200 employee.
int index = 0;
for (int i = 0; i < 200; i++)
{
var employee = new Employee();
//int categoryIndex = i % new Random().Next(1, 5);
//if (categoryIndex > 3)
// categoryIndex = 3;
index = index > 3 ? 0 : index;
employee.ID = i + 1;
employee.Name = name[index];
employee.Phone = phone[index];
employee.Email = email[index];
employee.City = city[index];
allEmployee.Add(employee);
index++;
}
}
public ActionResult Index(string employee_name, int? page)
{
ViewData["employee_name"] = employee_name;
int currentPageIndex = page.HasValue ? page.Value : 1;
IList<Employee> employees = this.allEmployee;
if (string.IsNullOrWhiteSpace(employee_name))
{
employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
}
else
{
employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
}
//var list =
if (Request.IsAjaxRequest())
return PartialView("_AjaxEmployeeList", employees);
else
return View(employees);
}
public ActionResult Paging(string employee_name, int? page)
{
ViewData["employee_name"] = employee_name;
int currentPageIndex = page.HasValue ? page.Value : 1;
IList<Employee> employees = this.allEmployee;
if (string.IsNullOrWhiteSpace(employee_name))
{
employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
}
else
{
employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
}
return View(employees);
}
}
JS references in the _Layout.cshtml
You have not described how exactly it is not working. but i will guess the most common issues which might be causing your issue
make sure you actually have a reference to the correct java script files. its not enough to have them in a folder, your page must link to them.
see the following link to see how you reference scripts on you page. http://www.w3schools.com/tags/att_script_src.asp
make sure you put in the correct path.
make sure you reference the *ajax.js files for ajax to work along with any other required files.
Finally I found the solution.
Since I was using jquery-1.11.1.js, in script file jquery.unobtrusive-ajax.js I had to replace calls to .live() with .on().
But simple find and replace was not right way which I found later. I found from other sources that I have to change completely those lines of code as the .on() works.
I replaced the code as below:
Non-working code with .live() function:
$("a[data-ajax=true]").live("click", function (evt) {
debugger;
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
$("form[data-ajax=true] input[type=image]").live("click", function (evt) {
debugger;
var name = evt.target.name,
$target = $(evt.target),
form = $target.parents("form")[0],
offset = $target.offset();
$(form).data(data_click, [
{ name: name + ".x", value: Math.round(evt.pageX - offset.left) },
{ name: name + ".y", value: Math.round(evt.pageY - offset.top) }
]);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$("form[data-ajax=true] :submit").live("click", function (evt) {
debugger;
var name = evt.target.name,
form = $(evt.target).parents("form")[0];
$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$("form[data-ajax=true]").live("submit", function (evt) {
debugger;
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault();
if (!validate(this)) {
return;
}
asyncRequest(this, {
url: this.action,
type: this.method || "GET",
data: clickInfo.concat($(this).serializeArray())
});
});
Working code with .on() function:
$(document).on("click", "a[data-ajax=true]", function (evt) {
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
$(document).on("click", "form[data-ajax=true] input[type=image]", function (evt) {
var name = evt.target.name,
$target = $(evt.target),
form = $target.parents("form")[0],
offset = $target.offset();
$(form).data(data_click, [
{ name: name + ".x", value: Math.round(evt.pageX - offset.left) },
{ name: name + ".y", value: Math.round(evt.pageY - offset.top) }
]);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$(document).on("click", "form[data-ajax=true] :submit", function (evt) {
var name = evt.target.name,
form = $(evt.target).parents("form")[0];
$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$(document).on("submit", "form[data-ajax=true]", function (evt) {
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault();
if (!validate(this)) {
return;
}
asyncRequest(this, {
url: this.action,
type: this.method || "GET",
data: clickInfo.concat($(this).serializeArray())
});
});
Thanks.
I an experimenting with MVC. I have a view which contains a dropdownlist and a table.
When I select an option from the dropdownlist, I want to get the data from my controller and update the view:
View:
<div>
<h2>Current Print Statistics</h2>
#using (Html.BeginForm())
{
#Html.DropDownList("LogTypes", new SelectList(Model.LogTypes, "Value", "Text"), new
{
id = "logType",
data_url = Url.Action("GetStatistics", "Home")
})
<table id="modelTable" class="table table-condensed">
<tr>
<th>RequestedOn</th>
<th>PrintedOn</th>
<th>Message</th>
<th>Success</th>
<th>TemplateName</th>
</tr>
<tbody>
#foreach (var item in Model.PrintLogs)
{
string css = (item.Success) ? "success" : "danger";
string link = (item.Success) ? "www.google.com" : string.Empty;
<tr class="#css">
<td>#item.RequestedOn</td>
<td>#item.PrintedOn</td>
<td>#item.Message</td>
#if (item.Success)
{
<td>#item.Success</td>
}
else
{
<td>#Html.ActionLink("False", "Index", "LogView", new { id = item.LogID }, null)</td>
}
<td>#item.TemplateName</td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$('#logType').change(function () {
console.log($(this).data('url'));
var selectedValue = $(this).val();
var table = $('#modelTable');
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
context: table,
data: { value: selectedValue },
success: function (result) {
$.each(result.PrintLogs,
function (index, log) {
$('<tr/>', {
html: $('<td/>', {
html: log.RequestedOn
}).after($('<td/>', {
html: log.PrintedOn
})).after($('<td/>', {
html: log.Success
})).after($('<td/>', {
html: log.Message
})).after($('<td/>', {
html: log.TemplateName
}))
}).appendTo(tableBody);
}
);
}
});
});
});
</script>
Controller:
[HttpGet]
public JsonResult GetStatistics(string value)
{
var request = LogTypeRequest.Last24H;
if (value == "0") request = LogTypeRequest.Last24H;
if (value == "1") request = LogTypeRequest.LastWeek;
if (value == "2") request = LogTypeRequest.LastMonth;
var model = new PrintServerModel
{
LogTypes = new List<ListItem>
{
new ListItem() {Text = "Last 24 Hours", Value = "0"},
new ListItem() {Text = "Last Week", Value = "1"},
new ListItem() {Text = "Last Month", Value = "2"}
},
PrintLogs = PrintServerService.GetPrinterLog(request)
};
return Json(model, JsonRequestBehavior.AllowGet);
}
Now when I try to debug in chrome, when the line $.ajax({ is reached it seems to jump to the end.
Ideally what I want is to display the data on start up and then when the user selects something from the dropdown, refresh the data.
Any help greafully appreciated!!
Odds are there is an error from the json call, you should add .done or error: to the end of it so you can see what your error is.
also there is a tab in chrome debug tool for watching the network calls, you may be able to see the response from the call in there with some additional details.
just looking over the ajax call, may want to change to have
data: JSON.stringify( { value: selectedValue }),
if you get more info i will do what i can to better my answer.
I got this error after I hit the Delete from Cart, Object reference not set to an instance of an object. This is happening in my partial View. Any idea on how to resolve this ?
TableContent.cshtml (partial view) from Panier
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Table Content";
}
<a href="#" class="TableContent">
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems) <=== error is happening here
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description, "Details", "Produit", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.PanierId">
#item.Quantite
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.PanierId"> Enlever du panier
</a>
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
</a>
Index.cshtml from Panier
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).remove();
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
$.get('#Url.Action("TableContent", "Panier")')
$("#TableContent").html(data); });
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<div id="table-content">
#Html.Partial("TableContent") <=== partial view call
</div>
PanierController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tp1WebStore3.Models;
using Tp1WebStore3.ViewModels;
namespace Tp1WebStore3.Controllers
{
public class PanierController : Controller
{
//
// GET: /Panier/
Tp1WebStoreDBEntities dbProduit = new Tp1WebStoreDBEntities();
//
// GET: /ShoppingCart/
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our ViewModel
var viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
// Return the view
return View(viewModel);
}
//
// GET: /Store/AddToCart/5
public ActionResult AddToCart(int id)
{
// Retrieve the album from the database
var addedProduit = dbProduit.Produits
.Single(produit => produit.ProduitId == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduit);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
//
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
/* return View("CartSummary"); */
}
//
// GET: /ShoppingCart/CartSummary
[ChildActionOnly]
public ActionResult CartSummary()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
ViewData["CartCount"] = cart.GetCount();
return PartialView("CartSummary");
}
public ActionResult TableContent()
{
return PartialView("TableContent");
}
}
}
did you make sure Model.CartItems is not null?
try this :
#if (Model.CartItems != null) { <=== add breakpoint here
foreach (var item in Model.CartItems) <=== error is happening here
{
...
}
}
and add a breakpoint on the if and check if the value is null ;-)
edited:
in the ajax responce, you can reload the partialview ...
success: function (result) {
$('#yourPartialViewContainerId').load('/Action/PartialView');
...
but be sure your foreach items is not null inside your partialView ...
so when the user click the edit link to edit one of the client (field) and another user have erase already that client how can show to the user that the client (field) is gone?
so I'am using TempData is another way to do it? i think jquery but i don't know how to use it properly
public ActionResult Edit (int id)
{
client cliente = db.Clients.Find(id);
if (cliente != null)
{
return View(cliente);
}
TempData["message"] = string.Format("this client have be erase for other user");
return RedirectToAction("Index");
}
edit:
and view is this
<table class="widgets">
<tr>
<th></th>
<th>
#Html.ActionLink("Nombre", "Index", new { ordenacion = ViewBag.NameSortParm, filtro = ViewBag.filtro })
</th>
</tr>
#foreach (var item in Model) {
<tr id="widget-id-#item.id">
<td>
#Html.ActionLink("Editar", "Edit", new { id=item.id }) |
#Ajax.ActionLink("Eliminar", "Eliminar", "Cliente",
new {item.id },
new AjaxOptions {
HttpMethod = "POST",
Confirm = string.Format("Esta Seguro que quiere eliminar '{0}'?", item.descripcion),
OnSuccess = "deleteConfirmation"
})
</td>
<td>
#Html.DisplayFor(modelItem => item.descripcion)
</td>
</tr>
}
</table>
i guees the script will be this? so i have to make my edit link like i did for the delete (eliminar) link using #Ajax.ActionLink right?
<script type="text/javascript">
var validateForEdit = function (id) {
var validateCallbackFunction = function (result) {
if (result) {
window.location = '/Client/Editar/' + id;
}
else {
window.Alert('this client have be erase for other user');
}
};
$.post('/Client/ValidateForEdit/', { id: id }, validateCallbackFunction, 'json');
}
</script>
Hi you can use following code to validate data before user can edit that
var validateForEdit = function (id) {
var validateCallbackFunction = function (result) {
if (result) {
window.location = '/Client/Edit/' + id;
}
else {
Alert('this client have be erase for other user');
}
};
$.post('/Client/ValidateForEdit/', { id: id }, validateCallbackFunction, 'json');
}
And your Action :
[HttpPost]
public JsonResult ValidateForEdit(int id)
{
var cliente = db.Clients.Find(id);
return cliente != null ? Json(true) : Json(false);
}
Edit : And you have to replace your following code
#Html.ActionLink("Editar", "Edit", new { id=item.id })
with this code :
<input class="button" type="button" value="Edit" onclick="validateForEdit(item.id)" />
Hope this help.