How to use ActionResult return null - asp.net-mvc

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

Related

Summernote image upload with .NET Core

Im really struggling to get SummerNote to upload an iamge in .NET core. The trouble is the IFormFile file parameter is null when a new image is uploaded.
I initialise Summernote using the following -
$('#MessageBody').summernote({
height: ($(window).height() - 300),
callbacks: {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
Here is the uploadImage function -
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
$.ajax({
url: '/EmailTemplate/UploadImage',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img>').attr('src', 'http://' + url);
$('#MessageBody').summernote("insertNode", image[0]);
alert(url);
var imgNode = document.createElement('img');
imgNode.src = url;
$('#MessageBody').summernote('insertNode', imgNode);
},
error: function(data) {
console.log(data);
}
});
And finally, here is the controller -
[HttpPost]
public async Task<IActionResult> UploadImage(IFormFile file)
{
string message;
var saveimg = Path.Combine(_hostingEnvironment.WebRootPath, "Images", file.FileName);
string imgext = Path.GetExtension(file.FileName);
if (imgext == ".jpg" || imgext == ".png")
{
using (var uploadimg = new FileStream(saveimg, FileMode.Create))
{
await file.CopyToAsync(uploadimg);
message = "The selected file" + file.FileName + " is saved";
}
}
else
{
message = "only JPG and PNG extensions are supported";
}
// return "filename : " + saveimg + " message :" + message;
return Content(Url.Content(saveimg));
}
The parameter is called file while the field name is image. To fix this use the same name, either file or image.
The IFormFile type represents the value of an input type=file field. IFormFile parameters are bound to fields based on their name. There may be many file fields in the same form so the type isn't enough to determine the field.
Field binding is explained in the Sources section of the Model Binding document.

JQuery ajax call blocks RedirectToAction

I have a view with an ajax call:
$.ajax({
url: "CreateChecklistCopies",
type: "POST",
data: JSON.stringify(drivers),
async: false,
contentType: "application/json; charset=utf-8",
});
The controller action performs some tasks and redirects to the index method of the controller:
[HttpPost]
public IActionResult CreateChecklistCopies([FromBody] object i_vm)
{
var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
int result = _obj.AddChecklistCopies(tmp);
if (result > 0)
return RedirectToAction("Index", new { SuccessMessage = "Checklists were successfully duplicated." });
else
return RedirectToAction("Index", new { ErrorMessage = "An error occurred when duplicating the checklist." });
}
The Index action is successfully executed but there's no forward to the index page happening:
[HttpGet]
public IActionResult Index(string FilterCreator, string salesPersonFilter, string SuccessMessage, string ErrorMessage)
{
if (FilterCreator == null)
{
FilterCreator = User.Identity.Name.Split("\\")[1];
}
else if (FilterCreator.ToLower() == "all")
{
FilterCreator = null;
}
var checklists = _obj.GetChecklists(true, FilterCreator, salesPersonFilter);
var salespersons = _obj.GetSalespersons();
var chlVm = _mapper.Map<List<ChecklistModel>, List<ChecklistListViewModel>>(checklists);
var ivm = new IndexViewModel
{
CheckLists = chlVm,
Salespersons = salespersons,
SuccessMessage = !string.IsNullOrEmpty(SuccessMessage) ? SuccessMessage : "",
ErrorMessage = !string.IsNullOrEmpty(ErrorMessage) ? ErrorMessage : ""
};
return View(ivm);
}
I played around with the async: false tag in the ajax call but that didn't help. Any ideas?
You cannot use RedirectToAction to action in an ajax call to redirect the entire page. Because the ajax response is limited to the ajax request scope only.
What you can do is return a json object instead of RedirectToAction like this:
[HttpPost]
public IActionResult CreateChecklistCopies([FromBody] object i_vm)
{
var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
int result = _obj.AddChecklistCopies(tmp);
JsonResult result = new JsonResult(new JsonSerializerSettings());
if (result > 0)
result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "Checklists were successfully duplicated." });
else
result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "An error occurred when duplicating the checklist." });
return result;
}
Then in the ajax call do this:
$.ajax({
url: "CreateChecklistCopies",
type: "POST",
data: JSON.stringify(drivers),
dataType: 'JSON',
async: false,
}).done(function (response) {
if (response != null) {
window.location = response.RedirectUrl;
//You can also use the IsRedirect and SuccessMessage property as needed
} else {
alert('There was a problem processing the request.');
}
}).fail(function () {
alert('There was a problem processing the request.');
});

"Value cannot be null.\r\nParameter name: input"

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

Calling a server side JsonResult method from JavaScript

I need to call the following JsonResult method:
JsonResult Delete(int pubId)
{
try
{
using (var ctx = new LibsysLiteContext())
{
var p = ctx.Publishers.Find(pubId);
var allPublisher = ctx.Publishers.ToList();
ctx.Publishers.Remove(p);
var total = allPublisher.Count();
return Json(new { success = true, data = allPublisher, total = total }, JsonRequestBehavior.AllowGet);
}
return Json(new RestResult { Success = true, Data = entity, Message = "Country has been deleted" }, JsonRequestBehavior.DenyGet);
return null;
}
catch (Exception e)
{
return Json(new RestResult { Success = true, Message = e.Message }, JsonRequestBehavior.DenyGet);
}
}
from a js function (deleteRows):
var deleteRows = function () {
Ext.Msg.confirm(
'Delete Rows', 'Are you sure?',
function(btn) {
if (btn == 'yes') {
var hh = Ext.getCmp('gg').deleteSelected();
ajax({
//action and controller
url: '#Url.Action( "Publisher", "Delete")',
data: { "Id": Id },
type: 'POST',
dataType: 'json',
});
}
});
};
which is called by a handler of the following button:
X.Button().ID("bntdelete").Text("delete").Icon(Icon.Delete).Handler("deleteRows();"),
It didn't work at all this way! How can I move from client side to the server side from a JavaScript function?
In general calling a serverside [Direct Method] from js you use App.direct.<Method>();
Hopefully you have resolved this by now but in your ajax call you are defining the type as post but what you show on the controller is set as the default get. you need to add
[HttpPost]
public JsonResult Delete(int id)...
to your controller

Sending Data From javaScript Which Is retrived from LocalStorage(WebSql) and pass to MVC Controller

db.transaction(
function (transaction) {
transaction.executeSql('INSERT INTO EmployeeTable(Firstname,Lastname,BirthDate,EmployeeType,MaritalStatus,Company,IsActive,Dependents) values(?,?,?,?,?,?,?,?)',
[Firstname.toString(), Lastname.toString(), BirthDate, parseInt(empType), parseInt(marital),Company.toString(),active, parseInt(Dependents)]);
transaction.executeSql('SELECT * FROM EmployeeTable', [], function (transaction, results) {
result = results;
alert(result.length);
for (i = 0; i < results.length; i++) {
var EmployeeID = results.rows.item(i).EmployeeID;
var Firstname = results.rows.item(i).Firstname;
var Lastname = results.rows.item(i).Lastname;
alert(results.rows.item(i).EmployeeID + " " + results.rows.item(i).Firstname + " " + results.rows.item(i).Lastname);
//var product = [productid, productname, price, qty];
//insertTableRow(product,i);
}
}, null);
}
);
am Using WEB SQL as Local Database
want to send data retrived from websql using
db.Transaction() method
to server controller.
Please Help On same.....
How should i transfer data to controller of mvc.....
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
if (Save(0, collection))
{
// List<char> bulkdata = collection["bulkdata"].ToList();
return RedirectToAction("Index");
}
else
{
return View("Edit");
}
}
catch
{
return View();
}
}
The following tutorial shows an example how to sync local db with a WCF Data Service endpoint. By combining this with the WebAPI tutorial you will be able to sync to the online DB with these lines:
function synchronizeData() {
offlinedb
.TodoItems
.filter("it.InSync === false")
.toArray(function (todoItems) {
onlinedb.addMany(todoItems);
onlinedb.saveChanges(function () {
todoItems.forEach(function (todoItem) {
offlinedb.attach(todoItem);
todoItem.InSync = true;
});
offlinedb.saveChanges(function () {
listLocalTodoItems();
listRemoteTodoItems();
});
});
})
}
You might try serializing your localstorage string and then send to the server...
ASP.NET MVC How to pass JSON object from View to Controller as Parameter

Resources