Ajax Not Working on Edit Method - asp.net-mvc

I have an ajax method for a cascading drop down list, similar to country - state drop down list. It works fine on Create method, but I can't get it to work on Edit method. I get this error on Edit:
POST http://localhost/Submissions/Edit/SomeAJAXMethod 500 (Internal Server Error)
There is an extra /Edit in the path that makes it not work. It works just fine on Create. I tried to add ~/. I get these errors on Create and Edit method:
POST http://localhost/Submissions/Edit/~/SomeAJAXMethod 404 (Not Found)
I tried to add ../. I get this error on Create, works fine on Edit:
POST http://localhost/SomeAJAXMethod 404 (Not Found)
How do I make it work on both Create and Edit?
Below is my controller.
//
// GET: /Submissions/Create
public ActionResult Create()
{
ViewBag.ActivityRejectCodeId = GetRejectCodesByActivity(0);
ViewBag.Activities = GetActivities();
ViewBag.Workstations = GetWorkstationsByActivity(0);
ViewBag.Platforms = GetPlatformsByWorkstation(0, 0);
ViewBag.Parts = GetPartsByPlatform(0, 0, 0);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name");
ViewBag.Technicians = GetTechnicians(0);
ViewBag.Shifts = GetShiftsByTechnician(0, 0);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO");
return View();
}
//
// POST: /Submissions/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(WorkOrderSubmission workordersubmission)
{
var activityId = Int32.Parse(Request.Form["ActivityId"]);
var workstationId = Int32.Parse(Request.Form["WorkstationId"]);
var platformId = Int32.Parse(Request.Form["PlatformId"]);
var partId = Int32.Parse(Request.Form["PartId"]);
var techId = Int32.Parse(Request.Form["TechnicianId"]);
var shiftId = Int32.Parse(Request.Form["ShiftId"]);
if (ModelState.IsValid)
{
// Get the PlatformStageId from the combination of (ActivityId, WorkstationId, PlatformId, PartId)
var rs = (from ps in db.PlatformStages
join wa in db.WorkstationActivities on ps.WorkstationActivityId equals wa.Id
join pp in db.PlatformParts on ps.PlatformPartId equals pp.Id
where ps.WorkstationActivity.ActivityId == activityId
&& ps.WorkstationActivity.WorkstationId == workstationId
&& ps.PlatformPart.PlatformId == platformId
&& ps.PlatformPart.PartId == partId
select new {
ps.Id
}).FirstOrDefault();
workordersubmission.PlatformStageId = rs.Id;
// Get TechnicianShiftId from the combination of (TechnicianId, ShiftId)
rs = (from ts in db.TechnicianShifts
where ts.TechnicianId == techId
&& ts.ShiftId == shiftId
select new
{
ts.Id
}).FirstOrDefault();
workordersubmission.TechnicianShiftId = rs.Id;
workordersubmission.SubmissionDate = DateTime.Now;
db.WorkOrderSubmissions.Add(workordersubmission);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.Activities = GetActivities(activityId);
ViewBag.Workstations = GetWorkstationsByActivity(activityId, workstationId);
ViewBag.Platforms = GetPlatformsByWorkstation(activityId, workstationId, platformId);
ViewBag.Parts = GetPartsByPlatform(activityId, workstationId, platformId, partId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.Technicians = GetTechnicians(techId);
ViewBag.Shifts = GetShiftsByTechnician(techId, shiftId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
//
// GET: /Submissions/Edit/5
public ActionResult Edit(int id = 0)
{
WorkOrderSubmission workordersubmission = db.WorkOrderSubmissions.Find(id);
if (workordersubmission == null)
{
return HttpNotFound();
}
var platformStageId = workordersubmission.PlatformStageId;
var technicianShiftId = workordersubmission.TechnicianShiftId;
// Get ActivityId, WorkstationId, PlatformId, PartId from PlatformStageId
var rs = (from ps in db.PlatformStages
join wa in db.WorkstationActivities on ps.WorkstationActivityId equals wa.Id
join pp in db.PlatformParts on ps.PlatformPartId equals pp.Id
where ps.Id == platformStageId
select new
{
ActivityId = wa.ActivityId,
WorkstationId = wa.WorkstationId,
PlatformId = pp.PlatformId,
PartId = pp.PartId
})
.FirstOrDefault();
ViewBag.Activities = GetActivities(rs.ActivityId);
ViewBag.Workstations = GetWorkstationsByActivity(rs.ActivityId, rs.WorkstationId);
ViewBag.Platforms = GetPlatformsByWorkstation(rs.ActivityId, rs.WorkstationId, rs.PlatformId);
ViewBag.Parts = GetPartsByPlatform(rs.ActivityId, rs.WorkstationId, rs.PlatformId, rs.PartId);
// Get TechnicianId, ShiftId from TechnicianShiftId
var rs2 = (from ts in db.TechnicianShifts
where ts.Id == technicianShiftId
select new //TechnicianShift
{
TechnicianId = ts.TechnicianId,
ShiftId = ts.ShiftId
})
.FirstOrDefault();
ViewBag.Technicians = GetTechnicians(rs2.TechnicianId);
ViewBag.Shifts = GetShiftsByTechnician(rs2.TechnicianId, rs2.ShiftId);
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
//
// POST: /WorkorderSubmissions/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(WorkOrderSubmission workordersubmission)
{
if (ModelState.IsValid)
{
db.Entry(workordersubmission).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.PlatformStageId = new SelectList(db.PlatformStages.OrderBy(p => p.Name), "Id", "Name", workordersubmission.PlatformStageId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.TechnicianShiftId = new SelectList(db.TechnicianShifts, "Id", "Description", workordersubmission.TechnicianShiftId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
Below is the AJAX call:
$(function () {
// Code that triggers when there is a change in Activity drop down.
$('#ActivityId').change(function () {
var activityId = $(this).val();
var url = 'GetRejectCodesByActivityJson';
// Empty the Reject Code drop down list.
$('#ActivityRejectCodeId').empty();
// Empty the Workstation, Platform, Part drop downs.
$('#WorkstationId').empty();
$('#PlatformId').empty();
$('#PartId').empty();
$('.showhide-workstation').show();
// AJAX call that re-populate Reject Code drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#ActivityRejectCodeId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#ActivityRejectCodeId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>')
});
},
error: function (ex) {
$('#ActivityRejectCodeId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
url = 'GetWorkstationsByActivityJson';
// AJAX call that re-populate Workstation drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#WorkstationId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#WorkstationId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#WorkstationId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
}); // END $('#ActivityId').change()
// Code that triggers when there is a change in Workstation drop down.
$('#WorkstationId').change(function () {
var activityId = $('#ActivityId').val();
var workstationId = $(this).val();
var url = 'GetPlatformsByWorkstationJson';
// Empty the Platform, Part drop downs.
$('#PlatformId').empty();
$('#PartId').empty();
$('.showhide-platform').show();
// AJAX call that re-populate Platform drop down depending on the Workstation selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId, workstationId: workstationId },
success: function (codes) {
$('#PlatformId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#PlatformId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#PlatformId').append('<option value=""></option>');
}
}); // END $.ajax() on GetPlatformsByWorkstationJson
}); // END $('#WorkstationId').change()

Related

How to convert array to send as query string?

In my view, I have checkboxes and some data displayed and button on each row to approve or reject requests put up.
I want to send my integer array to my action method but this cannot be done by just sending it to action query parameters and it would be like the picture below:
public int[] Ids
{
get { return new int[] { 1, 2, 3 }; }
set {}
}
public ActionResult Approval([ModelBinder(typeof(IntArrayModelBinder))] int[] ids)
{
...
return View(...);
}
#Html.ActionLink("Approve", "Approval", new {id = item.Ids, approvalAction = "approve"})
How do I implement the checkboxes to be checked and hover of the approve/reject actionlink will show the url with ../ids=1&ids=2&ids=3 instead of System.Int32[]?
Option 1: Send your array as a comma-separated string and then split them in your action like this :
#Html.ActionLink("Approve", "Approval", new { id = string.Join("," , Ids), approvalAction = "approve" } )
your action :
public ActionResult YourAction(string id , string approvalAction)
{
var ids = id.Split(',');
//rest of your action method business
}
Option 2:
another way to achieve your exactly url is to create your URL like this :
var baseUrl = Url.Action("YourAction", "YourController", null, Request.Url.Scheme);
var uriBuilder = new UriBuilder(baseUrl);
uriBuilder.Query = string.Join("&", Ids.Select(x => "ids=" + x));
string url = uriBuilder.ToString();
url += "&approvalAction=approve"
and your action would be like this :
public ActionResult YourAction(int[] ids , string approvalAction)
{}
<script>
function multiSelect(selectedArray, action) {
if (selectedArray[0] === undefined) {
alert("You have not selected any employee");
}
//example url
//..?ids=1&ids=2&ids=3&aprovalAction=approve
else {
var param = "";
var currUrl = "";
var idUrl = "";
idUrl = "ids=" + selectedArray[0];
for (var i = 1; i < selectedArray.length; ++i) {
idUrl += "&ids=" + selectedArray[i];
}
switch (action) {
case "Approve":
param = "approve";
break;
case "Reject":
param = "reject";
break;
}
currUrl = "approvalAction=" + param;
window.location.href = "?" + idUrl + "&" + currUrl;
}
}
</script>
<script>
$('#MultiApproveBtn').click(function () {
var selected = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
var x = document.getElementById("MultiApproveBtn").value;
//alert(selected);
multiSelect(selected, x);
})
</script>
<script>
$('#MultiRejectBtn').click(function () {
var selected = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
var x = document.getElementById("MultiRejectBtn").value;
//alert(selected);
multiSelect(selected, x);
})
</script>

jquery autocomplete passing parameters

I need help to pass parameters through JQuery's autocomplete. I have an input:
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchName" id="searchName" placeholder="Nom et/ou prénom" />
inside a form. When you type, an jquery autocomplete function launches a search in Active Directory and shows result in the drop down list:
$(document).ready(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserWhileTyping",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
$("#searchName").html(''),
response($.map(data, function (item) {
return {
label: item
}
}));
}
});
},
minLength: 4
})
});
$(document).ready(function(){
$('#searchName').on('autocompletechange change', function () {
$('#searchValue').html('You selected: ' + this.value);
}).change()});
For now I could only do it after a form validation: form is validated -> I load the users found and their unique id -> click on one link and it shows the user info thanks to their unique id passed through. What I want to do is: If you click on one of the autocomplete choices, it directly shows the information of your user.
Here is the code for the search while you type:
[HttpGet]
public ActionResult SearchUserWhileTyping(string name)
{
ADManager adManager = new ADManager();
List<string> lastName = adManager.SearchUserByName(name);
List<string> splitList = new List<string>();
if (lastName != null)
{
if (lastName.Count <= 10)
{
int inc = 0;
foreach(string splitter in lastName)
{
if (inc % 2 == 1)
{
splitList.Add(splitter);
}
inc++;
}
return Json(splitList, JsonRequestBehavior.AllowGet);
}
}
return null;
}
I use a splitter because another function allows me to search AD and returns several parameters (which will then be useful to immediately find a user by its unique id, that's my difficulty).
This calls the following function:
public List<string> SearchUserByName(string name)
{
try
{
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
var sidInBytes=new byte[0];
//anr permet de chercher tout utilisateur contenant "name"
search.Filter = "(&(objectClass=user)(anr=" + name + "))";
//search.Filter = "(&(objectClass=User) (name=" + name + "*))";
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("distinguishedName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
if (sResult.Properties["distinguishedName"][0].Equals(null) ||
sResult.Properties["displayName"][0].Equals(null))
continue;
displayName.Add(sResult.Properties["distinguishedName"][0].ToString());
displayName.Add(sResult.Properties["displayName"][0].ToString());
}
}
ldapConnection.Close();
ldapConnection.Dispose();
search.Dispose();
return displayName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
Finally, when I have my list of users, I can click on their link and I load info about the user using this function:
public List<KeyValuePair<string,string>> GetUserInfoBySAMAN(string sAMAccountName)
{
try
{
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.Filter = "(sAMAccountName=" + sAMAccountName + ")";
search.PropertiesToLoad.Add("objectSID");
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("memberOf");
search.PropertiesToLoad.Add("description");
search.PropertiesToLoad.Add("accountExpires");
search.PropertiesToLoad.Add("sAMAccountName");
result = search.FindOne();
///Conversion du SID en chaine de caractères
var sidInBytes = (byte[])result.Properties["objectSID"][0];
var sid = new SecurityIdentifier(sidInBytes, 0);
String time;
if (result.Properties["accountExpires"][0].ToString().Equals("0")|| result.Properties["accountExpires"][0].ToString().Equals("9223372036854775807"))
{
time = "Jamais";
}
else
{
///Conversion de la date en entier puis en date
DateTime dt = new DateTime(1601, 01, 02).AddTicks((Int64)result.Properties["accountExpires"][0]);
time = dt.ToString();
}
string desc="";
if (result.Properties.Contains("description"))
{
desc = result.Properties["description"][0].ToString();
}
else
{
desc = "Pas de description disponible";
}
userInfo = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("displayName",result.Properties["displayName"][0].ToString()),
new KeyValuePair<string, string>("memberOf", result.Properties["memberOf"][0].ToString()),
new KeyValuePair<string, string>("accountExpires",time),
new KeyValuePair<string, string>("description",desc),
new KeyValuePair<string, string>("sid",sid.ToString()),
new KeyValuePair<string, string>("sAMAccountName",result.Properties["sAMAccountName"][0].ToString())
/*lastName.Add(result.Properties["displayName"][0].ToString());
lastName.Add(result.Properties["memberOf"][0].ToString());
lastName.Add(sid.ToString());
lastName.Add(result.Properties["accountExpires"][0].ToString());
lastName.Add(result.Properties["description"][0].ToString());*/
};
return userInfo;
}
catch(Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
That last function doesn't work if I change sAMAccountName by distinguishedName because apparently this attribute cannot be used like that. I want to use distinguishedName and immediately have my object.
So what I need is to search while I type, and if I select one of the proposed choices, validating the form immediately send me to user info page.
Thanks for your help, hope it is clear enough
Edit I added a 2nd script that can get the value of selected item, but I need the data passed through the controller
If I understood right, autocomplete method has select event.
$(document).ready(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserWhileTyping",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
$("#searchName").html(''),
response($.map(data, function (item) {
return {
label: item
}
}));
},
select: function(e, ui)
{
//Just Example
$.get("UserController", {ID: ui.Id}).done(
function(data){
});
//Write your ajax post or get method
//that fetches user data directly as soon as
//the item in list clicked
}
});
},
minLength: 4
})
});
Edit: I saw your edit, so that you can use your GetUserInfoBySAMAN function for ajax get request inside select event (instead where I wrote "UserController"), and you have work for binding return data to the inputs or labels as well.

.Net RunTimeBinderException

I have a data content witch contains complex data I just need index names which seem in Dynamic View in data. In debug mode I can see the datas but cant get them..
You can see the contents of data in image below):
if(hits.Count() > 0)
{
var data = hits.FirstOrDefault().Source;
var dataaa = JsonConvert.DeserializeObject(hits.FirstOrDefault().Source);
}
I found a solution with checking if selected index has documents; if yes,
I take the first document in index, and parse it to keys(field names) in client.
here is my func:
[HttpPost]
public ActionResult getIndexFields(string index_name)
{
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(
node,
defaultIndex: index_name
);
var esclient = new ElasticClient(settings);
var Documents = esclient.Search<dynamic>(s => s.Index(index_name).AllTypes().Source());
string fields = "";
if (Documents.Documents.Count() > 0)
{
fields = JsonConvert.SerializeObject(Documents.Documents.FirstOrDefault());
var data = Documents.Documents.FirstOrDefault().Source;
return Json(new
{
result = fields,
Success = true
});
}
return Json(new
{
result = "",
Success = false
});
}
and my js:
$.ajax({
url: "getIndexFields?index_name=" + $(this).val(),
type: "POST",
success: function (data) {
if (data.Success) {
var fields = JSON.parse(data.result);
var fields_arr = [];
$.each(fields, function (value, index) {
fields_arr.push(
{
id: value,
label: value
})
});
options.filters = fields_arr;
var lang = "en";//$(this).val();
var done = function () {
var rules = $b.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
options.rules = rules;
}
options.lang_code = lang;
$b.queryBuilder('destroy');
$('#builder').queryBuilder(options);
};
debugger
if ($.fn.queryBuilder.regional[lang] === undefined) {
$.getScript('../dist/i18n/query-builder.' + lang + '.js', done);
}
else {
done();
}
}
else {
event.theme = 'ruby';
event.heading = '<i class=\'fa fa-warning\'></i> Process Failure';
event.message = 'User could not create.';
event.sticky = true;
$("#divfailed").empty();
$("#divfailed").hide();
$("#divfailed").append("<i class='fa fa-warning'></i> " + data.ErrorMessage);
$("#divfailed").show(500);
setTimeout(function () {
$("#divfailed").hide(500);
}, 3000);
}
},
error: function (a, b, c) {
debugger
event.theme = 'ruby';
event.heading = '<i class=\'fa fa-warning\'></i> Process Failure';
event.message = 'Object could not create.';
$("#divfailed").empty();
$("#divfailed").hide();
msg = c !== "" ? c : a.responseText;
$("#divfailed").append("<i class='fa fa-warning'></i> " + msg);
$("#divfailed").show(500);
setTimeout(function () {
$("#divfailed").hide(500);
}, 3000);
}
});

String instead of data

I'm trying to get data from the controller
something like this:
public IEnumerable<Custom> Search(string searchText = "")
{
return new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };
}
But angular gives me this
m
u
s
i
c
p
o
r
t
a
l
.
C
o
n
t
r
o
l
l
e
r
s
.
C
u
s
t
o
m
[
]
I tried add http.headers but nothing.
My code:
var musicportal = angular.module('musicportal', []);
musicportal.controller('SearchController', ['$scope', '$http', function ($scope, $http) {
$scope.answer = "awesome";
$scope.search = function (text) {
$scope.answer = text;
$scope.pms = [];
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = data;
});
$scope.searchText = "";
}
}]);
You should return data as json e.g.
public ActionResult Search(string searchText = "")
{
return Json(new { Foo = "Hello" }, JsonRequestBehavior.AllowGet);
}
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = data.Foo;
});
Now, in your case, you have a list, so you need to convert that into JSON. You can do that in ASP.NET MVC using JsonSerializer e.g.
public ActionResult Search(string searchText = "")
{
string json = "";
var items = new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };
using (var writer = new StringWriter())
using (var jsonWriter = new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, items);
json = writer.ToString();
}
return Json(json, JsonRequestBehavior.AllowGet);
}
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = JSON.Parse(data);
});
You may need to play about with this code, it's not perfect first time, but hopefully it will give you a head start.

Forms authentication cookie is not persisting or is not getting past through an ajax request?

I am at a loss as to why my authentication cookie disappears. I am using Valums Ajax Upload in conjunction with a couple other ajax requests to build a user's avatar. It is very random as to when the cookie disappears. I can upload 4 files without an issue, then 2 files maybe (after another login). It seems after I call the CreateAvatar method, that is where there might be an issue, but like I said, it doesn't happen all the time. What am I missing?
JavaScript:
$(function () {
//This is the Upload Method
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
//fileCount--;
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
//alert('There was an error when trying to save ' + fileName);
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
parent.$.fn.colorbox.close();
}
}
});
});
//This Creates the Avatar Object
function createAvatar(fileName, imageId) {
var avatarUploadModel = {
UploadFileName: fileName,
UserId: '#ViewBag.UserId',
ImageId: imageId
};
$.ajax({
url: '/Admin/Avatar/CreateAvatar/',
type: 'POST',
cache: false,
timeout: 100000,
data: JSON.stringify(avatarUploadModel),
contentType: 'application/json; charset=utf-8',
dataType: "json",
error: function (xhr, status, error) {
alert(error + " " + status);
},
success: function (data) {
if (data.success) {
loadAvatar(data.avatarModel);
return true;
} else {
return false;
}
}
});
}
//This loads the partial to view the avatar after upload
function loadAvatar(avatarModel) {
$.ajax({
url: '/Admin/Avatar/AvatarEdit',
type: 'GET',
cache: false,
timeout: 100000,
data: avatarModel,
dataType: "html",
error: function (xhr, status, error) {
alert(error + " " + status);
},
success: function (data) {
$("#avatarOriginal").html(data);
}
});
}
Login Method:
var user = _userService.GetByUserName(model.Username);
var authTicket = new
FormsAuthenticationTicket(1, //version
user.Id.ToString(), // user name
DateTime.Now,
DateTime.Now.AddMinutes(40), //Expiration
model.RememberMe, //Persistent,
user.Username);
var encTicket = FormsAuthentication.Encrypt(authTicket);
HttpContext.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return Json(new {success = true, url = model.ReturnUrl}, JsonRequestBehavior.AllowGet);
Upload Method on Controller:
[HttpPost]
public ActionResult AvatarUpload(HttpPostedFileBase fileData)
{
var id = Guid.NewGuid();
string fileName;
var serverPath = Server.MapPath("~/Areas/Admin/TemporaryUploads/");
if (fileData != null)
{
var fileRenamed = System.IO.Path.GetFileName(id + "_" + fileData.FileName);
fileName = Server.MapPath("~/Areas/Admin/TemporaryUploads/" + fileRenamed);
fileData.SaveAs(fileName);
}
else
{
var ajaxUploadFileData = Request["qqfile"];
fileName = Path.Combine(serverPath, id + "_" + Path.GetFileName(ajaxUploadFileData));
using (var output = System.IO.File.Create(fileName))
{
Request.InputStream.CopyTo(output);
}
}
return Json(new {success = true, file = fileName, imageId = id}, JsonRequestBehavior.AllowGet);
}
Create Avatar Method:
[HttpPost]
public ActionResult CreateAvatar(AvatarModel avatarModel)
{
try
{
var image = new WebImage(avatarModel.UploadFileName).Resize(400, 400, true);
var imageFileName = Path.GetFileName(avatarModel.UploadFileName);
var avatar = new Domain.YogaDiVitaContext.Model.Avatar()
{
CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
UserId = avatarModel.UserId,
Image = new Image()
{
CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
OriginalImageRelativePath = "original/" + imageFileName
}
};
var user = UserService.FindById(avatarModel.UserId);
if (user.Avatar != null)
RemoveAvatar(user.Avatar);
avatar = _avatarService.Create(avatar);
user.Avatar = avatar;
UserService.Update(user);
var basePath = Server.MapPath("~/" + avatar.ToAvatarBasePath(GlobalVariables.AvatarPath));
Directory.CreateDirectory(basePath);
Directory.CreateDirectory(basePath + "/thumbnail");
Directory.CreateDirectory(basePath + "/fullsize");
Directory.CreateDirectory(basePath + "/original");
image.Save(Server.MapPath("~/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath)));
avatarModel.Width = image.Width;
avatarModel.Height = image.Height;
avatarModel.Top = image.Height*0.1;
avatarModel.Left = image.Width*0.9;
avatarModel.Right = image.Width*0.9;
avatarModel.Bottom = image.Height*0.9;
avatarModel.OriginalImagePath = "/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath);
System.IO.File.Delete(avatarModel.UploadFileName);
return Json(new {success = true, avatarModel}, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
return Json(new {message = exception.Message}, JsonRequestBehavior.AllowGet);
}
}
Load Avatar Partial:
public ActionResult AvatarEdit(AvatarModel avatarModel)
{
return PartialView("AvatarCropPartial", avatarModel);
}

Resources