Passing javascript values through html.actionlink - javascript

I am developing an export function where I need to pass some values available in javascript code to a controller through #Html.ActionLink. Basically user will be selecting start date , end date & phase number which on clicking a button exports the whole table into an excel. Below i am attaching the code of js, html, cs files.
js code:
<script type="text/javascript">
$(document).ready(function () {
$("#departing").datepicker({ dateFormat: 'yy-mm-dd' });
$("#returning").datepicker({ dateFormat: 'yy-mm-dd' });
$("button").click(function () {
var selected = $("#dropdown option:selected").text();
var departing = $("#departing").val();
var returning = $("#returning").val();
});
});
var selPhaseNumber = "A";
$(document).ready(function () {
//fetch and bind the year dropdown list
$('input[type=radio][name=rdbPhase]').change(function () {
if ($(this).val() == "Phase I") {
selPhaseNumber = "I";
}
else if ($(this).val() == "Phase II") {
selPhaseNumber = "II";
}
else {
selPhaseNumber = "A";
}
})
})
</script>
html code:
<div class="col-lg-6">
<div class="col-lg-3">#Html.ActionLink("Export to Excel", "ExportSubmittedTicketToExcel", "ExportExcel", null, new { #class = "btn btn-primary", #id = "btnExport"})</div>
</div>
(call should be something like this)
(api/ProjectBilling/SubmittedExportBillDetails/" + startdate + '/' + enddate + '/' + selPhaseNumber)
controller code:
[Route("ExportExcel/ExportSubmittedTicketToExcel/")]
public ActionResult ExportSubmittedTicketToExcel(string MemberName)
{
try
{
if (System.Web.HttpContext.Current.Session["DisplayName"] != null)
{
List<ExportExcelModelSubmitted> Result = new List<ExportExcelModelSubmitted>();
using (var client = new HttpClient())
{
int UserID = Convert.ToInt32(System.Web.HttpContext.Current.Session["CurrentUserID"]);
client.BaseAddress = new Uri(WebApiURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/ProjectBilling/SubmittedExportBillDetails/" + startdate + '/' + enddate + '/' + selPhaseNumber).Result;
if (response.IsSuccessStatusCode)
{
Result = response.Content.ReadAsAsync<List<ExportExcelModelSubmitted>>().Result;
}
else
{
string returncode = response.StatusCode.ToString();
return Content("<script language='javascript' type='text/javascript'>alert('" + returncode + "');</script>");
}
}
DataTable dt = new DataTable();
dt = Result.ToDataTable();
MemoryStream stream = new MemoryStream();
using (ExcelPackage pck = new ExcelPackage(stream))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("BillingDetails");
ws.Cells["A1"].LoadFromDataTable(dt, true);
ws.Cells.AutoFitColumns();
using (ExcelRange rng = ws.Cells[1, 1, 1, dt.Columns.Count])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));
rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
}
pck.SaveAs(stream);
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=SubmittedBilling.xls");
Response.BinaryWrite(stream.ToArray());
Response.End();
}
return View();
}
else
{
return RedirectToAction("Login", "Home");
}
}
catch (Exception ex)
{
throw ex;
}
}

You can do it by Ajax Call also
[Route("ExportExcel/ExportSubmittedTicketToExcel/")]
public ActionResult ExportSubmittedTicketToExcel(datetime startDate,datetime endDate,string phaseNumber)
{
//logic
string fullPath = Path.Combine(Server.MapPath("~/MyFiles"), file);
return File(fullpath, "application/vnd.ms-excel", file);
}
and
$ajax({
cache: false,
url: '/ExportExcel/ExportSubmittedTicketToExcel',
data: {'startDate':startdate,'endDate':enddate,'phaseNumber':selPhaseNumber}
success: function (data){
window.location = data.fullpath;
}
})

Related

MVC Partial View Not Displaying Image

I have a Kendo Grid where one of the columns is actually a link to open a pop up to view the image. I'm able to get the image back but I'm unsuccessful so far. Here is what I have so far-
Controller-
public ActionResult OpenImagePopUp(int? id)
{
Help request2 = new Help();
request2.id = id;
var response = apiHelp.GetHelpRecords(request2);
if (response.Error != null)
{
ErrorLogRequest errorReq = new ErrorLogRequest()
{
LogDate = DateTime.Now,
LogMethod = "GetHelpRecords",
LogPage = "Canopy Help",
LogPerson = User.Identity.Name,
LogInfo = response.Error.ErrorCode + " " + response.Error.ErrorMessage + " " + response.Error.ExceptionObject.Message
};
apiErrorLog.InsertErrorLog(errorReq);
}
var helpRecords = response.data.Select(s => new Help()
{
Image = s.Image
}).FirstOrDefault();
var base64string = Convert.ToBase64String(helpRecords.Image);
request2.ImgSrcBase64 = String.Format("data:image/gif;base64,{0}", base64string);
return PartialView("ImagePopUp", request2);
}
My View / Javascript -
<div>
#(Html.Kendo().Window()
.Name("ImagePopUp")
//.LoadContentFrom("OpenPopUpWindow", "BlueButtonView")
.Draggable()
.Actions(actions => actions.Close())
.Modal(true).Visible(false)
.HtmlAttributes(new { style = "margin: 10px" })
.LoadContentFrom("OpenImagePopUp", "Help")
.Draggable()
.Resizable()
.Width(600)
.Actions(actions => actions.Close())
)
</div>
function showImage(e) {
var grid = $("#CanopyHelpGrid").getKendoGrid();
var item = grid.dataItem($(e.target).closest("tr"));
$("#ImagePopUp").data("kendoWindow").open().center(true);
$.ajax({
datatype: "image",
type: "GET",
url: '#Url.Action("OpenImagePopUp", "Help")',
data: { id: item.id },
success: function (data) {
//$("#imgPopUp").attr('src', data);
}
})
}
Then finally my partial view -
#model OSH.Domain.Models.CanopyHelp.Help
<img id="imgPopUp" alt="Image" src='#Model.ImgSrcBase64'>
I tried to convert the array to a base64 string then format it to be the image source but I keep seeing no image.
As Stephen have suggested, adding this to my ajax solved the problem!
$.ajax({
datatype: "html",
type: "GET",
url: '#Url.Action("OpenImagePopUp", "Help")',
data: { id: item.id },
success: function (html) {
$("#ImagePopUp").html(html);
$("#ImagePopUp").data("kendoWindow").open().center(true);
}
})
I also made my controller return html content instead and removed the image tag on my partial view-
public ActionResult OpenImagePopUp(int? id)
{
if (id != null)
{
string html = string.Empty;
Help request2 = new Help();
request2.id = id;
var response = apiHelp.GetHelpRecords(request2);
if (response.Error != null)
{
ErrorLogRequest errorReq = new ErrorLogRequest()
{
LogDate = DateTime.Now,
LogMethod = "GetHelpRecords",
LogPage = "Canopy Help",
LogPerson = User.Identity.Name,
LogInfo = response.Error.ErrorCode + " " + response.Error.ErrorMessage + " " + response.Error.ExceptionObject.Message
};
apiErrorLog.InsertErrorLog(errorReq);
}
var helpRecords = response.data.Select(s => new Help()
{
id = s.id,
Image = s.Image
}).Where(w => w.id == id).FirstOrDefault();
if (helpRecords.Image != null)
{
var base64string = Convert.ToBase64String(helpRecords.Image);
request2.ImgSrcBase64 = string.Format("data:image/gif;base64,{0}", base64string);
html = string.Format("<img id='imgPopUp' src='{0}' alt='Image'/>", request2.ImgSrcBase64);
return Content(html, "text/html");
}
else
{
html = "<h4>This record has no image attached!</h4>";
return Content(html, "text/html");
}
}
else return new EmptyResult();
}

error when updating records in web api.

After selecting the department to update.
a submit button is click.
this error appear
{"readyState":4,"reponseText":"{\"Message\":\"Object reference not set to an instance of an object.\",\"StackTrace\":\" at WebService.yearEndClosing(String strDate, String endDate, String cond, String cal, String entryUser)in WebService.cs:line 390\",\"ExecptionType\":\"System.NullReferenceException\"}","responseJSON":{"Message":"Object reference not set to an instance of an object.","StackTrace":" at WebService.yearEndClosing(String strDate, STring endDate, String cond, String val, String entryUser) in WebService.cs:line 390\",\"ExecptionType\":\"System.NullReferenceException\"},"status":500, "statusText":"Internal Server Error"}
The code for submit button.
//Function for submit button event
$(function () {
$("#btnSubmit").bind("click", function (e) {
if (confirm("Click [OK] to proceed on forfiet the leave of selected department.")) {
var selectedDept = new Array();
var i = 0;
//Get checked checkbox in the list
$(".bodyfont input").each(function () {
if ($(this).is(":checked")) {
selectedDept[i] = $(this).val();
i++;
}
});
var ddlVal = $("[id*='ddlVal']").val();
var endDate = $("[id*='tEnd']").val();
var strDate = $("[id*='tStart']").val();
if (strDate != "" && endDate !="" && i > 0) {
ShowLoading();
$.ajax({
type: "POST",
url: "WebService.asmx/yearEndClosing",
data: "{ 'strDate':'" + strDate + "', 'endDate':'" + endDate +
"', 'cond':'" + ddlVal + "', 'val':'" + JSON.stringify(selectedDept) +
"', 'entryUser':'" + getLoginID() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var json_obj = data.d;//parse JSON
if (json_obj != null) {
if (json_obj.length == 0) {
alert("All selected department/employee in date range are closed!")
}
else {
//deserialize json object to string
var table = "";
$("#tblNotClose tr").remove();
$.each(json_obj, function (index, YrEndClosing) {
table += "<tr><td>" + YrEndClosing.empID + "</td><td>" + YrEndClosing.empName + "</td></tr>";
});
if (table != "") {
header = "<tr><th>Emp ID</th><th>Emp No</th></tr>";
$("#tblNotClose").append(header);
$("#tblNotClose").append(table).removeClass("hidden");
}
$("#modalResult").modal('show');
}
}
else {
alert("Error on closing");
}
ShowDetails();
},
error: function (error) {
alert(JSON.stringify(error));
}
});
e.preventdefault;
}
else {
alert("Due Date is not seleceted to forfiet the leave");
}
}
});
});
And it is this alert(JSON.stringify(error)); which display the error.
Now lets breakdown the issue. base on my understanding
the error is telling that there is something going on with the parameter in
yearEndClosing(String strDate, String endDate, String cond, String cal, String entryUser) which is on line 390
here i the code
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<YrEndClosing> yearEndClosing(string strDate, string endDate, string cond, string val, string entryUser)
{
eLeaveModule em = new eLeaveModule();
JavaScriptSerializer json = new JavaScriptSerializer();
List<string> arrayString = json.Deserialize<List<string>>(val);
DateTime dtStr = Convert.ToDateTime(strDate, CultureInfo.GetCultureInfo("en-us").DateTimeFormat);
DateTime dtEnd = Convert.ToDateTime(endDate, CultureInfo.GetCultureInfo("en-us").DateTimeFormat);
List<YrEndClosing> result = em.yearEndClosing(dtStr, dtEnd, cond, arrayString, entryUser);
if (result.Count > 0)
{
string relDate = Regex.Replace(string.Format("{0:s}", DateTime.Now), #"[^0-9a-zA-Z]+", "");
string subPath = #" C:\webOutput\eHRMS\Closing\";
bool exists = System.IO.Directory.Exists(subPath);
if (!exists)
System.IO.Directory.CreateDirectory(subPath);
using (StreamWriter writer = new StreamWriter(subPath + "ClosingList" + relDate + ".txt"))
{
for (int i = 0; i < result.Count; i++)
{ writer.WriteLine(result[i].empID + "-" + result[i].empName); }
}
}
return result;
}
USEFUL INFORMATION
The code work in server 2
The same code not working in server 1 (current issue)
No error when running on local by visual studio for web
May i know what could be the issue.
I am still trying to even locate where the possible issue is at.

Calling a c# function from code behind using javascript

I need to call a c# function in my code behind using a javascript where i set two variables that i need to call my function with these variables, following my codes:
C# code behind:
public string CallWebMethod(string url, Dictionary<string, string> dicParameters)
{
try
{
byte[] requestData = this.CreateHttpRequestData(dicParameters);
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.KeepAlive = false;
httpRequest.ContentType = "application/json; charset=utf-8";
httpRequest.ContentLength = requestData.Length;
httpRequest.Timeout = 30000;
HttpWebResponse httpResponse = null;
String response = String.Empty;
httpRequest.GetRequestStream().Write(requestData, 0, requestData.Length);
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream baseStream = httpResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(baseStream);
response = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private byte[] CreateHttpRequestData(Dictionary<string, string> dic)
{
StringBuilder sbParameters = new StringBuilder();
foreach (string param in dic.Keys)
{
sbParameters.Append(param);//key => parameter name
sbParameters.Append('=');
sbParameters.Append(dic[param]);//key value
sbParameters.Append('&');
}
sbParameters.Remove(sbParameters.Length - 1, 1);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(sbParameters.ToString());
}
and this is my javascript :
<script>
function SendNeedHelpLinkTrace() {
var keysToSend = ['pCatchLinkVirement', 'pCatchLinkCarteBancaire', 'pCatchLinkRechargePaiementFactureTelecom', 'pCatchLinkPaiementVignetteImpotTaxe', 'pCatchLinkPaiementFactureEauElectricite', 'pCatchLinkServiceFatourati', 'pCatchLinkCihExpress', 'pCatchLinkEdocuments']
var lChannelId = document.getElementById('<%= HiddenChannelId.ClientID%>').value;
var lServiceId = "900149";
var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;
//alert(lClientId);
var lData = keysToSend.reduce(function(p,c){
var _t = sessionStorage.getItem(c);
return isEmpty(_t) ? p : p + ' | ' + _t;
}, '')
function isEmpty(val){
return val === undefined || val === null;
}
var lCollect;
console.log(lClientId);
console.log(lData);
alert(lData);
// this is the dictionnary:
lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;
console.log(lDataCollected);
//this is the url:
var url="http://10.5.230.21:4156/CatchEvent.asmx/CollectData";
sessionStorage.clear();
}
How should i proceed ?

Input array is longer

I try to display data in grid view through web method and jquery function so i try this. I try to display gridview when user select value from drop-down and select dates from calendar
$(function () {
$('[ID*=search_data]').on('click', function () {
var fromdate = $('[ID*=fromdate]').val();
var todate = $('[ID*=todate]').val();
var regiondrop = $('[ID*=regiondrop] option:selected')[0].value;
var GridView1 = $('[ID*=GridView1]');
var obj = {};
obj.fromdate = fromdate;
obj.todate = todate;
obj.regiondrop = regiondrop;
Getdataa(obj);
});
});
function Getdataa(obj) {
//alert('1');
$.ajax({
type: "POST",
url: "WebForm1.aspx/search_data",
data: "{'fromdate':'" + obj.fromdate + "','todate':'" + obj.todate + "','regiondrop':'" + obj.regiondrop + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
$("#GridView1").empty();
if (result.d.length > 0) {
$("#GridView1").append(
"<tr><th>ID</th><th>OName</th><th>Reg No</th><th>Speed</th></tr>");
for (var i = 0; i < result.d.length; i++) {
$("#GridView1").append("<tr><td>" +
result.d[i].ID+ "</td> <td>" +
result.d[i].OName + "</td> <td>" +
result.d[i].Reg No+ "</td> <td>" +
result.d[i].Speed+ "</td></tr>");
}
}
else {
$("#GridView1").hide();
$("#Label1").text("No Data");
}
},
error: function (error) {
alert("error");
}
});
}
WebMethod
[WebMethod]
public static DataTable search_data(DateTime fromdate, DateTime todate, string regiondrop)
{
try
{
T1 ts = new T1();
var dq = (from vv in ts.tblVe
join rv in ts.tblRe on vv.ID equals rv.ID
join re in ts.tblReg on rv.RID equals re.RID
where
re.Region == regiondrop
&& re.StartDate <= fromdate
&& re.EndDate >= todate
orderby
vv.ID,
rv.OwnerName
select new
{
ID=rv.ID,
OName = rv.OName ,
RegNo = rv.RegNo,
Speed = rv.Speed ,
}).ToList();
DataTable dt = new DataTable();
dt.Rows.Add(dq);
return dt;
}
catch (Exception)
{
throw new Exception();
}
}
in var dq.. dq show this data
[0] = { ID = 1, OName = "Khan", RegNo = "AJ-24",Speed = "124" } [1] = { ID = 2, OName = "Shah", RegNo = "AL-91",Speed = "95" }
UPDATE
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("OName", typeof(string));
dt.Columns.Add("RegNo", typeof(string));
dt.Columns.Add("Speed", typeof(string));
dt.Rows.Add(dq);
return dt;
and exception occur
Unable to cast object of type 'System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]' to type 'System.IConvertible'.Couldn't store <System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]> in ID Column.
You will have to add the columns in you datatable
dt.Columns.Add();
for more information : https://msdn.microsoft.com/en-us/library/hfx3s9wd(v=vs.110).aspx

Refresh model after post-request in ASP.MVC

I'm developping a webApp with MVC.
I have a view with cirkles displaying a value and a slider,
when you slide the cirkles need to display the new value.
I send the new value with a POST from my AJAX call to the controller,
which does a minor calculation with the value and give it back to the view
so the cirkles can display the updated value.
However my view still keeps using the startvalue.
#model UGT.UI.Web.MVC.Models.BelastingViewModel
<script language="JavaScript">
var config1 = liquidFillGaugeDefaultSettings();
#{
teller = 1;
string naam_var = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam = "fillgauge" + teller;
naam_var = "gauge" + teller;
#: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
teller++;
}
}
function toonCirkels() {
#{
teller = 1;
naam = "fillgauge" + teller;
string naam_var2 = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam_var2 = "gauge" + teller;
// #: gauge1.update("#Html.DisplayFor(modelItem => cat.Value)");
// #: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
// #: #naam_var2.update("#Html.DisplayFor(modelItem => cat.Value)");
teller++;
}
//#:gauge1.update("500");
}
}
public class BelastingsController : Controller
{
private BegrotingsManager begrotingsManager = new BegrotingsManager();
private int gemeenteId = 54;
private double loon = 200;
private BelastingViewModel belastingen = new BelastingViewModel();
// GET: Belastings
public ActionResult Index()
{
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return View(belastingen);
}
[HttpPost]
public ActionResult Index(String loon)
{
this.loon = Double.Parse(loon);
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return new HttpStatusCodeResult(HttpStatusCode.OK);
// return RedirectToAction("Index");
}
namespace UGT.UI.Web.MVC.Models
{
public class BelastingViewModel
{
public IDictionary<Categorie, double> Belasting { get; set; }
}
}
d3.selectAll('.range').on('change', function () {
this.value = parseInt(this.value);
if (this.value < 0) this.value = 0;
else if (this.value > 5000) this.value = 5000;
var loon = this.value;
var loonString = "€" + loon;
d3.select('.range_value').html(loonString);
sendLoon(loon, loonString);
});
}
function sendLoon(loon, loonString) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "/Belastings",
type: "POST",
data: JSON.stringify({ "loon": loon }),
success: function () {
// window.location.reload();
toonCirkels();
},
error: function () { }
});
}
The success of your Ajax call calls 'toonCirkels' which only contains razor generated code which is filled on page load. The content of this method never changes as it contains ONLY razor generated code and thus will always have the same logic with the same values.

Categories