"Value cannot be null.\r\nParameter name: input" - asp.net-mvc

I made an ajax call. From ajax the values are passing exactly correct but I am getting that error. I try to find the reason, but failed to locate that.
I try to debug the code but it's showing nothing meaningful.
var obj = {
Mode: mode,
TissueRequestFeeID: mode == 1 ? 0 : data.TissueRequestFeeID,
TissueRequestID: viewBagRequestId,
FeeTypeID: data.FeeTypeID,
OtherFee: data.OtherFee,
Fee: data.Fee,
};
}
var TissueRequestFeeobj = {
TissueRequestFeeData: JSON.stringify(obj)
}
console.log(TissueRequestFeeobj);
var url = rootPath + "api/RequestApi/SaveAndUpdateRequest";
$.ajax({
url: url,
type: 'POST',
data: TissueRequestFeeobj,
success: function (TissueRequestFeeID) {
console.log(TissueRequestFeeID);
}
});
API code:
[System.Web.Http.HttpGet]
[System.Web.Http.ActionName("UpdateTissueRequestFee")]
public HttpResponseMessage UpdateTissueRequestFee(HttpRequestMessage request,int Mode, int TissueRequestFeeID, int TissueRequestID,
int FeeTypeID,string Fee,string OtherFee)
{
try
{
EISDataAccess objDAL = new EISDataAccess();
int i = 0;
SqlParameter[] p = new SqlParameter[7];
p[i] = new SqlParameter("#Mode", SqlDbType.Int);
p[i].Value = Mode;
i++;
p[i] = new SqlParameter("#TissueRequestFeeID", SqlDbType.Int);
p[i].Value = TissueRequestFeeID;
i++;
p[i] = new SqlParameter("#TissueRequestID", SqlDbType.Int);
p[i].Value = TissueRequestID;
i++;
p[i] = new SqlParameter("#OtherFee", SqlDbType.VarChar);
p[i].Value = OtherFee;
i++;
p[i] = new SqlParameter("#Fee", SqlDbType.VarChar);
p[i].Value = Fee;
i++;
p[i] = new SqlParameter("#CreatedBy", SqlDbType.VarChar);
p[i].Value = SessionManager.Current.UserDetails.AppUserId;
i++;
p[i] = new SqlParameter("#ModifiedBy", SqlDbType.VarChar);
p[i].Value = SessionManager.Current.UserDetails.AppUserId;
i++;
var RequestID = objDAL.ExecuteDataset(connectionString, CommandType.StoredProcedure, "Distribution_SaveRequest", p);
return request.CreateResponse(HttpStatusCode.OK, p[1].Value);
}
catch (SqlException ex)
{
return ProcessHttpRequestException(request, ex);
}
catch (Exception ex)
{
return ProcessHttpRequestException(request, ex);
}
}

You are passing TissueRequestFeeobj in your ajax call which contains an object with the key TissueRequestFeeData but in the action method, the attributes of `TissueRequestFeeData' have been mentioned as separate parameters. Hence you are getting null values.
Instead you should try passing JSON.stringify(obj) directly in the ajax call. Something like this:
var obj = {
Mode: mode,
TissueRequestFeeID: mode == 1 ? 0 : data.TissueRequestFeeID,
TissueRequestID: viewBagRequestId,
FeeTypeID: data.FeeTypeID,
OtherFee: data.OtherFee,
Fee: data.Fee,
};
var url = rootPath + "api/RequestApi/SaveAndUpdateRequest";
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(obj),
success: function (TissueRequestFeeID) {
console.log(TissueRequestFeeID);
}
});

Related

User.Identity.IsAuthenticated always false when calling from restSharp

I have a web application in which I was authenticating user like below
$.ajax({
method: 'POST',
data: JSON.stringify(SaveDetails),
url: Utils.getWebApiUrl() + "/api/account/isLoggedIn",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'bearer ' + access_token);
}
})
code in the controller below
[HttpPost]
[Route("api/account/isLoggedIn")]
public IHttpActionResult IsLoggedIn(Dictionary<string, string> Parameters)
//(string UserLoginLogId)
{
if (User?.Identity?.IsAuthenticated == true)
{
if (Parameters.Count() > 0)
{
string userLoginLogId = Convert.ToString(Parameters["UserLoginLogId"]);
string userRefreshToken = Convert.ToString(Parameters["userRefreshToken"]);
if (!string.IsNullOrWhiteSpace(userLoginLogId))
{
DocPro.DMS.BusinessLayer.IAccess.IUser a = (DocPro.DMS.BusinessLayer.IAccess.IUser)DALFinder.GetInstance(typeof(DocPro.DMS.BusinessLayer.IAccess.IUser));
//int LoginTimeOut = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Login-TimeOut"]);
if (a.IsLoggedInAsPerRefreshToken(Convert.ToInt64(userLoginLogId), userRefreshToken))
return Ok();
else
return NotFound();
}
else
return NotFound();
}
else
return Ok();
}
else
return NotFound();
}
and it was working fine, now I changed the code to the following
Dictionary<string, string> p = new Dictionary<string, string>();
p.Add("UserLoginLogId", Convert.ToString(userId));
p.Add("userRefreshToken", Convert.ToString(RefreshToken));
RestClient client = new RestClient(Convert.ToString(URL));
client.Timeout = -1;
RestRequest request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(p);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + accessToken);
IRestResponse<SPResponse> response = client.Execute<SPResponse>(request);
var result = JsonConvert.DeserializeObject<SPResponse>(response.Content);
but the following key "User?.Identity?.IsAuthenticated" is always showing false and I don't understand the reason.
while I do google I found a solution like below
var isAusorized = (Request.Properties["MS_HttpContext"] as HttpContextWrapper).User.Identity.IsAuthenticated;
but I don't understand how it worked and should I use this or not.

How to use ActionResult return null

i am using ajax call to save data and print the receipt.
My ajax call is
$.ajax({
type: "POST",
url: "/Payments/AddPayment",
data: frm,
dataType: "json",
success: function (objData) {
//ResetFormData();
if (objData.AMENDEDBY == "") {
strMsg = "Added Sucessfully";
}
else {
strMsg = "Updated Sucessfully";
}
AlertData(strMsg, "Payments", "success");
window.location.assign("/Report/PrintReport?objData=" + objData.REFNO);
}
});
Data saved accurately and after that i want to take print of the saved data.
i am using
window.location.assign("/Report/PrintReport?objData=" + objData.REFNO);
my Controller code for pritn crystal report is
public ActionResult PrintReport(string objData)
{
try
{
//Report Object
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reports/Accounts"), "CrystalReport1.rpt"));
rd.RecordSelectionFormula = "{TBL_ACC_VOUCHERS_MASTER.REFNO}='" + objData + "'";
//Report Connection object
ReportRepo objReport = new ReportRepo();
rd = objReport.GetReportConnections(rd);
//Print Report Direct to Default Printer
PrintDocument pdoc = new PrintDocument();
string PrinterName = pdoc.PrinterSettings.PrinterName;
rd.PrintOptions.PrinterName = PrinterName;
rd.PrintToPrinter(1, true, 0, 0);
return new EmptyResult();
}
catch
{
throw;
}
}
Report printed successfully but as return i am getting default view with reset values. I want to get the same view without any change.
i also used
return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
but same result

Ajax Not Working on Edit Method

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()

.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);
}
});

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