File upload using popup form, MVC and AJAX always 'NULL' - c#

I'm using the code from this tutorial to upload rows to a SQL Server table and one of the new requirements it's getting files stored into the server for "Evidence" purposes, so in the form I have the following code:
#using (Html.BeginForm("AnadirLic", "Licencia", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return SubmitForm(this)" }))
{
#Html.HiddenFor(model => model.idLicencia)
<div class="form-group">
<label>Tipo de especialista: </label>
#Html.DropDownList("tipoEspecialista", new List<SelectListItem>{
new SelectListItem{ Value="1", Text = "Medico"},
new SelectListItem{ Value="2", Text = "Dentista"},
new SelectListItem{ Value="3", Text = "Matrona"},})
<small class="form-text text-muted">Ejercicio</small>
</div>
<div class="form-group">
<label>Cargar Evidencia</label>
#*#Html.TextBoxFor(model => model.rutaEvidencia, new { #class = "form-control", #type = "file" })*#
#*#Html.TextBoxFor(model => model.rutaEvidencia, new { #class = "form-control", #type = "file", enctype = "multipart/form-data" })*#
<input type="file" id="FileUpload" />
<small class="form-text text-muted">Máximo 4MB, .pdf, .jpg, .png</small>
</div>
<div class="input-group">
<input type="submit" value="Subir" class="btn btn-primary" style="margin-right:10px"/>
<input type="reset" value="Limpiar campos" class="btn btn-primary" />
</div>
And the AJAX function looks like this:
<script>
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Llenar nuevo reposo',
height: 500,
width: 1300,
close: function () {
Popup.dialog('destroy').remove();
}
})
}
)
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
// FILE VALIDATOR / COUNT
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var archivo = document.getElementById("FileUpload").files[i];
form.append("FileUpload", archivo);
}
//IF VALID UPLOAD TO SQL
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
$('#tablaLicencia').DataTable().ajax.reload()
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
</script>
Finally the C#:
[HttpPost]
public ActionResult AnadirLic(licenciasUsuario lic)
{
using (TH_mantenedorLicenciasEntities db = new TH_mantenedorLicenciasEntities())
{
var fechaYMD = DateTime.Now.ToString("yyyyMMdd");
var fechaHM = DateTime.Now.ToString("hhmm");
var InputFileName = "";
var ServerSavePath = "";
for (int i = 0; i < Request.Files.Count; i++)
{
var archivo = Request.Files[i];
InputFileName = Path.GetFileName(archivo.FileName);
ServerSavePath = Path.Combine(Server.MapPath("~/evCargadas") + fechaYMD + "_" + fechaHM + "_" + InputFileName);
//Save file to server folder
archivo.SaveAs(ServerSavePath);
}
ViewBag.Message = "Archivo subido correctamente.";
db.licenciasUsuario.Add(lic);
db.SaveChanges();
//UPDATE CON RUTA DE ARCHIVO
lic.rutaEvidencia = ServerSavePath;
db.Entry(lic).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return Json(new { success = true, message = "Licencia guardada exitosamente." }, JsonRequestBehavior.AllowGet);
}
}
What I've faced is that the FileUpload is always null and using HttpPostFileBase returns the same, therefore the method throws a null exception to the Entity and based on some answers on SO, MVC conflicts with these kind of ajax apps.
System.Data.Entity.Validation.DbEntityValidationException: 'Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.'
Is it possible to emulate a function that allows/force a file upload into a project folder using the same popup thing?

<input type="file" id="FileUpload" /> lets you to select single file. In submit function you are accessing files property which is available only for multiple files selection.
So, either add multiple to your input tag <input type="file" id="FileUpload" multiple />
or modify submit function to use "value" property instead of files property.
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
// FILE VALIDATOR / COUNT
/*var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var archivo = document.getElementById("FileUpload").files[i];
form.append("FileUpload", archivo);
}*/
var archivo = document.getElementById("FileUpload").Value;
form.append("FileUpload", archivo);
//IF VALID UPLOAD TO SQL
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
$('#tablaLicencia').DataTable().ajax.reload()
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}

Related

How to pass the DropDownList value selected to my controller function to then show the output in a TextArea

I am trying to select the file name in my DropDownList to then call my GetFile function with the name file of the select box to then output it in a TextArea.
But i am unable to pass the data to GetFile( nameFile)
My DropDownList that contains my xml files name:
<div class="card" style="padding:20px">
<h4 class="mb-0">Sélection d'un fichier model XML </h4>
#Html.DropDownListFor(model => model.ListeFichiers, ((Dictionary<string, string>)Model.ListeFichiers).Select(e => new SelectListItem() { Text = e.Key, Value = e.Value }).ToList(),
new { #class = "form-control", #id = "listeFichierTransmettre" })
</div>
My GetFile function which takes as a parameter the filename retrieved from DropDownList
public string GetFile(string nomFichier)
{
string path = #"C:\xmlFiles\" + nomFichier;
string fileContent;
using (StreamReader streamReader = new StreamReader(#path, Encoding.UTF8))
{
fileContent = streamReader.ReadToEnd();
}
return fileContent;
}
After that i want to output the GetFile string returned in a TextArea :
<div class="card-body" id="XMLResult">
#Html.TextArea("Info", new { cols = "75", rows = "15", #readonly = "readonly", #disabled = "disabled", style = "min-width:100% !important;" })
</div>
What i tried but my file name is always null so clearly i am doing something wrong:
$(document).ready(function () {
$("#listeFichierTransmettre").change(function () {
$.ajax({
type: "POST",
url: '/Information/GetFile',
data: $('#listeFichierTransmettre').serialize(),
dataType: 'json',
success: function (result) {
console.log(result);
}
})
return false;
});
});
change script to :
$(document).ready(function() {
$("#listeFichierTransmettre").change(function() {
$.ajax({
type: "POST",
url: '/Information/GetFile',
data: {
nomFichier: $("#listeFichierTransmettre").find(":selected").val()
},
dataType: 'json',
success: function(result) {
console.log(result);
$("#Info").val(result);
}
})
return false;
});
});

ASP.NET MVC - Can't upload information and a file in the same Ajax Post Call

I need to upload information do a database, I have my controller which receives the params and then I uso them based on my business needs.
When I try to upload only the params it works but when I try to upload the params + the uploaded file in the file upload it doesn't work.
I've tried to change the way of the code was build but it didn't work
HTML:
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Departamento</label>
#Html.DropDownList("Departamentos", (IEnumerable<SelectListItem>)ViewBag.Departamentos, "Selecione um Departamento", new { #class = "form-control select2", #id = "DDL_DEP", onchange = "FillBooks(this.value);" })
</div>
<!-- /.form-group -->
<!-- /.form-group -->
<div class="form-group">
<label>Tipo</label>
#Html.DropDownList("Tipo", (IEnumerable<SelectListItem>)ViewBag.Tipo, "Selecione um Tipo", new { #class = "form-control select2", #id = "DDL_TIPO" } )
</div>
<div class="form-group">
<label>Título do Ticket</label>
#Html.TextBox("TicketTitulo", null, new { #class = "form-control" })
</div>
<div class="form-group">
<label>Descrição do Ticket</label>
#Html.TextArea("TicketDesc", null, new { #class = "form-control", #style = "resize: Vertical; " })
</div>
<div class="form-group">
<label for="exampleInputFile">Anexo</label>
<input type="file" id="exampleInputFile">
<p class="help-block">Insira o seu anexo.</p>
</div>
<div class="box-footer">
<button type="submit" id="btn-save" class="btn btn-primary pull-right">Guardar</button>
<button type="submit" class="btn btn-default">Voltar</button>
</div>
</div>
</div>
jQuery:
$(document).ready(function () {
$("#btn-save").click(function (e) {
var IdDep = $('#DDL_DEP').val();
var IdTipo = $('#DDL_TIPO').val();
var TituloTicket = $('#TicketTitulo').val();
var DescTicket = $('#TicketDesc').val();
var formData = new FormData();
var file = document.getElementById("exampleInputFile").files[0];
formData.append("exampleInputFile", file);
$.ajax({
url: '#Url.Action("InsertTicket", "Tickets")',
type: "POST",
dataType: "JSON",
cache: false,
contentType: false,
processData: false,
data: { a: IdDep, b: IdTipo, c: TituloTicket, d: DescTicket, e: formData },
success: function (data) {
},
error: function (error) {
alert(error.responseText);
}
});
});
})
Controller:
public ActionResult InsertTicket(int a, int b, string c, string d, HttpPostedFileBase e)
{
// BUSINESS CODE THAT I CAN'T SHOW BUT IT DOESN'T MATTER
}
Try this :
$(document).ready(function () {
$("#btn-save").click(function (e) {
var IdDep = $('#DDL_DEP').val();
var IdTipo = $('#DDL_TIPO').val();
var TituloTicket = $('#TicketTitulo').val();
var DescTicket = $('#TicketDesc').val();
var formData = new FormData();
var file = document.getElementById("exampleInputFile").files[0];
formData.append("e", file);
formData.append("a", IdDep );
formData.append("b", IdTipo);
formData.append("c", TituloTicket);
formData.append("d", DescTicket);
$.ajax({
url: '#Url.Action("InsertTicket", "Tickets")',
type: "POST",
dataType: "JSON",
cache: false,
contentType: false,
processData: false,
data: formData ,
success: function (data) {
},
error: function (error) {
alert(error.responseText);
}
});
});
})

The data is not saving in db using Pop-up Window after publish the application in Local host mvc4?

Hi I have one issue that is the data is not saving in db using Pop-up Window after Local host. I will explain my issue clearly.I Have one view called Customer. In that I have one field called Area and also i keep one add button near to that field.
Area
when i click the + button it will open the popup window. The pop window is mention below
Area Pop winodw
When i build and run the application and open this view and click the + button and enter all the details and click the save button it saving the value in db. All are working fine. But after i publish my applciation and open this view and click the + button it open the pop-up window. Untill this its working fine. But when i enter all the details and click the save button it not saving the data in Db. This is the issue. After my publish my application the datat is not saving in Db using pop-up window. But in Normal run it is perfectly working.
After Publishing the popup window
its working upto
$('#AreaID').append($('').val(data).text(Area));
but the saving is not saving in db. But all are working fine in normal run that is savinf data using pop-up is perfectly working in normal application running. But after i host my application in local host thi spopup window is not correctly working.
My View Code
<div id="Area">
<div class="col-sm-3">
<span style="color: #f00">*</span>
#Html.LabelFor(model => model.Area, new { #class = "control-label" })+
<div id="dialog-modal" title="Add New Area" style="display:none">
<div class="box-body">
<span class="red">*</span>
#Html.Label("Area", new { #class = "control-label" })
#Html.TextBoxFor(model => model.Area, new { #class = "form-control", type = "text", id = "AreaName" })
#Html.ValidationMessageFor(model => model.Area)
#Html.Label("City")
#Html.DropDownListFor(model => model.CityID, new SelectList(string.Empty, "Value", "Text"), "Please select a City", new { #class = "form-control required", type = "text", id = "City" })
<div class="box-footer">
<input id="Button1" class="btn btn-primary" type="button" value="Save" onclick="SaveArea()" />
</div>
</div>
</div>
#Html.DropDownList("AreaID", null, "Select", new { #class = "form-control required" })
</div>
</div>
My J query Code
<script type="text/javascript">
$(function () {
debugger
$("#dialog-modal").dialog({
resizable: false,
width: 500,
maxHeight: 400,
draggable: true,
dialogClass: 'main-dialog-class',
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
},
open: function () {
var closeBtn = $('.ui-dialog-titlebar-close');
closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>');
},
close: function () {
var closeBtn = $('.ui-dialog-titlebar-close');
closeBtn.html('');
},
});
$("#modal-opener").click(function () {
debugger
$("#dialog-modal").dialog("open");
});
});
function onSuccess() {
$("#dialog-modal").dialog("close");
}
function SaveArea() {
debugger
var url = '#Url.Action("Customer", "AddAreaInfo", new { area = "Sales" })';
var customerContact = $('#modalform').serialize(); // must have a <form id="modalform"> in the popup
var Area = $("#AreaName").val();
var CityID = $("#City").val();
var AreaAdd = { "Area": '' + Area + '', "CityID": CityID };
$.post("/Sales/Customer/AddAreaInfo", AreaAdd, function (data) {
$('#AreaID').append($('<option><option>').val(data).text(Area));
$('#AreaID').val(data);
alert ("Success")
});
}
$(function () {
$.ajax(
'#Url.Action("GetCity", "Customer", new { Area = "Sales" })',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#City').append('<option value="' + value.CityID + '">' +value.DisplayName + '</option>');
});
}
});
});
Controller
public JsonResult AddAreaInfo(CustomerViewModel objareaVM)
{
var objAreaID = Guid.NewGuid();
ViewBag.CityID = new SelectList(db.Cities, "CityID", "DisplayName", objareaVM.CityID);
var ObjArea = new Area()
{
AreaID = objAreaID,
DisplayName = objareaVM.Area,
PrintName = objareaVM.Area,
CityID = objareaVM.CityID,
IsActive = true,
IsDeleted = false,
CreatedDate = DateTime.Now,
EditedDate = DateTime.Now,
LastActiveOn = DateTime.Now,
RowID = Guid.NewGuid(),
CreatedSessionID = Guid.NewGuid(),
EditedSessionID = Guid.NewGuid(),
OfflineMode = false,
OfflineID = Guid.NewGuid()
};
db.Areas.Add(ObjArea);
db.SaveChanges();
ModelState.Clear();
return Json(objAreaID);
}
public JsonResult GetCity()
{
return Json(db.Cities.ToList(), JsonRequestBehavior.AllowGet);
}
I itself clear my issue . I like to share my answer . why it is not saving in db is the path to controller in j-query is not corrrect.
Finally I correct my j-query code
The answer is
J query Code
function SaveArea() {
debugger
var url = '#Url.Action("AddAreaInfo", "Customer", new { area = "Sales" })';
var customerContact = $('#modalform').serialize(); // must have a <form id="modalform"> in the popup
var Area = $("#AreaName").val();
var CityID = $("#City").val();
var AreaAdd = { "Area": '' + Area + '', "CityID": CityID };
$.post(url, AreaAdd, function (data) {
$('#AreaID').append($('<option><option>').val(data).text(Area));
$('#AreaID').val(data);
alert ("Success")
});
}
Before I gave my path as
var url = '#Url.Action(" Customer", "AddAreaInfo", new { area = "Sales" })';
Now i change that to
var url = '#Url.Action("AddAreaInfo", "Customer", new { area = "Sales"})';
So the issue got cleared and finally it save the data in DB.

unable to upload multiple image file ng-file-upload

My Html code:
<div class="col-md-6">
<img ngf-src="!picFile.$error && picFile" style="height: 150px; width: 200px;">
<input type="file" ngf-select ng-model="picFile" name="file"
accept="image/*" ngf-max-size="2MB"><b>Picture</b><br />
</div>
<div class="col-md-6">
<img ngf-src="!sigFile.$error && sigFile" style="height: 150px; width: 200px;">
<input type="file" ngf-select ng-model="sigFile" name="file"
accept="image/*" ngf-max-size="2MB"><b>Signature</b><br />
</div>
And My angular code
$scope.SaveNewJoinHolder = function (picFile, sigFile) {
if (investor_validity == 1) {
if ($scope.newJoinHolderForm.$valid) {
if (typeof $scope.newJoinHolder.DOB == undefined) {
$scope.newJoinHolder.DOB = null;
}
else {
var datefilter = $filter('date');
$scope.newJoinHolder.DOB = datefilter($scope.newJoinHolder.DOB, 'dd/MM/yyyy');
$scope.newJoinHolder.birth_date = dateconfigservice.FullDateUKtoDateKey($scope.newJoinHolder.DOB);
}
Upload.upload(
{
url: '/InvestorManagement/JoinHolder/SaveNewJoinHolder',
method: 'POST',
fields: $scope.newJoinHolder,
file: { picFile: picFile, sigFile: sigFile },
async: true
})
.success(function () {
toastr.success('Submitted Successfully');
}).error(function () {
toastr.success('Failed');
});
}
}
};
I debugged the code and I got both of the file while debugging. But it is not calling my C# method
public JsonResult SaveNewJoinHolder(tblJoinHolder joinHolder, HttpPostedFileBase picFile, HttpPostedFileBase sigFile)
{
joinHolderFactory = new JoinHolderFactory();
try
{
joinHolder.membership_id = SessionManger.BrokerOfLoggedInUser(Session).membership_id;
joinHolder.changed_user_id = User.Identity.GetUserId();
joinHolder.changed_date = DateTime.Now;
joinHolder.is_dirty = 1;
byte[] image = new byte[picFile.ContentLength];
picFile.InputStream.Read(image, 0, picFile.ContentLength);
joinHolder.photo = image;
byte[] signature = new byte[sigFile.ContentLength];
sigFile.InputStream.Read(image, 0, sigFile.ContentLength);
joinHolder.signature = signature;
joinHolderFactory.Add(joinHolder);
joinHolderFactory.Save();
return Json(new { data = "Successfully Saved Data", success = true });
}
catch (Exception ex)
{
return Json(new { data = ex.Message, success = false });
}
}
What is the problem here?
If I try to upload single image it is working.
Before version 7.2.0 you couldn't specify a map as file option so you had to do
Upload.upload(
{
url: '/InvestorManagement/JoinHolder/SaveNewJoinHolder',
method: 'POST',
fields: $scope.newJoinHolder,
file: [picFile, sigFile],
fileFormDataName: ['picfile', 'sigFile'],
})
But since version 7.2.0 your original code should work.
You can verify the network tab of your browser to make sure that the file form data is being sent to the server.

MVC Paging not working in AJAX Form

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.

Categories

Resources