C# and ajax call - c#

//Javascript function
function SaveAndUpdateProjectMaster() {
var CompanyCode = '';
var ProjectName = '';
var ProjectDescription = '';
var ProjectType = '';
var LocationSite = '';
var Client = '';
var Latitude = '';
var Longitude = '';
var Status = '';
var FirstLevelApprover = '';
var SecondLevelApprover = '';
var ThirdLevelApprover = '';
var userComment = '';
var CrudType = '';
var Id = '';
//$('#ddlDivision').val();
//$('#ddlRegionPrm').val();
//$('#ddlCountryPrm').val();
Id = $('#HdxtProjectId').val();
CompanyCode = $('#ddlCompanyPrm').val();
ProjectName = $('#txtProjectnamePrm').val();
ProjectDescription = $('#txtProjectDescriptionPrm').val();
ProjectType = $('#ddlProjecttypePrm').val();
LocationSite = $('#TxtLocationPrm').val();
Client = $('#TxtClientPrm').val();
Latitude = $('#TxtLatitudePrm').val();
Longitude = $('#TxtLongitudePrm').val();
Status = $('#hdnPMStatus').val();
FirstLevelApprover = $('#TxtFirstLevelPrm').val();
SecondLevelApprover = $('#TxtSecondLevelPrm').val();
ThirdLevelApprover = $('#TxtThirdlevel').val();
userComment = $('#txtUserComment').val();
CrudType=$('#hdnBtnType').val();
var obj = {};
obj.Id = Id;
obj.CompanyCode = CompanyCode;
obj.ProjectName = ProjectName;
obj.ProjectDescription = ProjectDescription;
obj.ProjectType = ProjectType;
obj.LocationSite = LocationSite;
obj.Client = Client;
obj.Latitude = Latitude;
obj.Longitude = Longitude;
obj.Status = Status;
obj.FirstLevelApprover = FirstLevelApprover;
obj.SecondLevelApprover = SecondLevelApprover;
obj.ThirdLevelApprover = ThirdLevelApprover;
obj.userComment = userComment;
obj.CrudType = CrudType;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ProjectMaster.aspx/SaveAndUpdateProject",
//data: JSON.stringify({ Id:Id,CompanyCode: CompanyCode, ProjectName: ProjectName, ProjectDescription: ProjectDescription, ProjectType: ProjectType, LocationSite: LocationSite, Client: Client, Latitude: Latitude, Longitude: Longitude, Status: Status, FirstLevelApprover: FirstLevelApprover, SecondLevelApprover: SecondLevelApprover, ThirdLevelApprover: ThirdLevelApprover, userComment: userComment, CrudType: CrudType }),
data: JSON.stringify({ Id: Id, CompanyCode: CompanyCode, ProjectName: ProjectName, ProjectDescription: ProjectDescription, ProjectType: ProjectType, LocationSite: LocationSite, Client: Client, Latitude: Latitude, Longitude: Longitude, Status: Status, FirstLevelApprover: FirstLevelApprover, SecondLevelApprover: SecondLevelApprover, ThirdLevelApprover: ThirdLevelApprover, userComment: userComment, CrudType: CrudType }),
dataType: "json",
success: function (data) {
if (data != '') {
debugger;
data = $.parseJSON(data.d);
data = $.parseJSON(data.d);
$('#ProjectMasterModal').hide();
var divison = $('#ddlDivision').val();
var country = $('#ddlCountryPrm').val();
var company = $('#ddlCompanyPrm').val();
var project = $('#ddlProjMaster').val();
//var masterVal = $('#hdnPMStatus').val();
GetRecord(divison,country,company,project,1);
alert(data.Msg);
CancelWarningCategory();
}
}
});
}
//C# WebMethod
[WebMethod]
public static string SaveAndUpdateProject(string Id,string CompanyCode, string ProjectName, string ProjectDescription, string ProjectType,string LocationSite, string Client, string Latitude, string Longitude, string Status, string FirstLevelApprover, string SecondLevelApprover,string ThirdLevelApprover,string userComment,string CrudType)
//public static string SaveAndUpdateProject(string Id)
{
//string CompanyCode=string.Empty;
//string ProjectName=string.Empty;
//string ProjectDescription=string.Empty;
//string ProjectType=string.Empty;
//string LocationSite=string.Empty;
//string Client=string.Empty;
//string Latitude=string.Empty;
//string Longitude=string.Empty;
//string Status=string.Empty;
//string FirstLevelApprover=string.Empty;
//string SecondLevelApprover=string.Empty;
//string ThirdLevelApprover=string.Empty;
//string userComment=string.Empty;
//string CrudType=string.Empty;
string res = string.Empty;
UserMsg obj = new UserMsg();
try
{
String Result = string.Empty;
BLL_ManageProject BLLProject = new BLL_ManageProject();
//if (btnProjectsave.Text == "Add New")
//{
if (CrudType == "Add New")
{
SqlParameter[] paramSaveProject = new SqlParameter[19];
paramSaveProject[0] = new SqlParameter("#CompanyCode", CompanyCode);
paramSaveProject[1] = new SqlParameter("#ProjectName", Convert.ToString(ProjectName));
paramSaveProject[2] = new SqlParameter("#ProjectDescription", Convert.ToString(ProjectDescription));
paramSaveProject[3] = new SqlParameter("#ProjectType", ProjectType);
paramSaveProject[4] = new SqlParameter("#LocationSite", Convert.ToString(LocationSite));
paramSaveProject[5] = new SqlParameter("#Client", Convert.ToString(Client));
paramSaveProject[6] = new SqlParameter("#Latitude", Convert.ToString(Latitude == "" ? "0.00" : Latitude));
paramSaveProject[7] = new SqlParameter("#Longitude", Convert.ToString(Longitude == "" ? "0.00" : Longitude));
paramSaveProject[8] = new SqlParameter("#IsActive", Convert.ToInt32(Status));
paramSaveProject[9] = new SqlParameter("#FirstLevelApprover", Convert.ToString(FirstLevelApprover));
paramSaveProject[10] = new SqlParameter("#SecondLevelApprover", Convert.ToString(SecondLevelApprover));
paramSaveProject[11] = new SqlParameter("#ThirdLevelApprover", Convert.ToString(ThirdLevelApprover));
paramSaveProject[12] = new SqlParameter("#PageName", HttpContext.Current.Request.Url.Segments.Last());
paramSaveProject[13] = new SqlParameter("#Title", "Insert Project Master");
paramSaveProject[14] = new SqlParameter("#UserComment", userComment);
paramSaveProject[15] = new SqlParameter("#SystemComment", "");
paramSaveProject[16] = new SqlParameter("#Revision", 0);
paramSaveProject[17] = new SqlParameter("#CreatedBy", (!string.IsNullOrEmpty(HttpContext.Current.Session["WindowsID"].ToString())) ? HttpContext.Current.Session["WindowsID"].ToString() : null);
paramSaveProject[18] = new SqlParameter("#CreatedDate", System.DateTime.Now);
Result = BLLProject.SaveProjectMaster(paramSaveProject);
if (Result == "1")
{
obj.Code = "1";
obj.Msg = GlobalConst.strInsertSuccess;
}
else if (Result == "2")
{
obj.Code = "2";
obj.Msg = GlobalConst.strRecordExists;
}
else
{
obj.Code = "0";
obj.Msg = GlobalConst.strInsertFaliure;
}
}
else if (CrudType == "Update")
{
SqlParameter[] paramSaveProject = new SqlParameter[20];
paramSaveProject[0] = new SqlParameter("#CompanyCode",CompanyCode);
paramSaveProject[1] = new SqlParameter("#ProjectName", Convert.ToString(ProjectName));
paramSaveProject[2] = new SqlParameter("#ProjectDescription", Convert.ToString(ProjectDescription));
paramSaveProject[3] = new SqlParameter("#ProjectType", ProjectType);
paramSaveProject[4] = new SqlParameter("#LocationSite", Convert.ToString(LocationSite));
paramSaveProject[5] = new SqlParameter("#Client", Convert.ToString(Client));
paramSaveProject[6] = new SqlParameter("#Latitude", Convert.ToString(Latitude == "" ? "0.00" : Latitude));
paramSaveProject[7] = new SqlParameter("#Longitude", Convert.ToString(Longitude == "" ? "0.00" :Longitude));
paramSaveProject[8] = new SqlParameter("#IsActive", Convert.ToInt32(Status));
paramSaveProject[9] = new SqlParameter("#FirstLevelApprover", Convert.ToString(FirstLevelApprover));
paramSaveProject[10] = new SqlParameter("#SecondLevelApprover", Convert.ToString(SecondLevelApprover));
paramSaveProject[11] = new SqlParameter("#ThirdLevelApprover", Convert.ToString(ThirdLevelApprover));
paramSaveProject[12] = new SqlParameter("#ProjectId", Id);
paramSaveProject[13] = new SqlParameter("#PageName",HttpContext.Current.Request.Url.Segments.Last());
paramSaveProject[14] = new SqlParameter("#Title", "Update Project Master");
paramSaveProject[15] = new SqlParameter("#UserComment", userComment);
paramSaveProject[16] = new SqlParameter("#SystemComment", "");
paramSaveProject[17] = new SqlParameter("#Revision", 0);
paramSaveProject[18] = new SqlParameter("#CreatedBy", (!string.IsNullOrEmpty(HttpContext.Current.Session["WindowsID"].ToString())) ? HttpContext.Current.Session["WindowsID"].ToString() : null);
paramSaveProject[19] = new SqlParameter("#CreatedDate", System.DateTime.Now);
Result = BLLProject.UpdateProjectMaster(paramSaveProject);
if (Result == "1")
{
obj.Code = "1";
obj.Msg = GlobalConst.strUpdateSuccess;
//BindProjectGrid(ddlDivision.SelectedItem.Value, ddlCountryPrm.SelectedItem.Value, ddlCompanyPrm.SelectedItem.Value, ddlProjMaster.SelectedValue.ToString());
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strUpdateSuccess + "');", true);
//btnCancelProject_Click(sender, e);
}
else if (Result == "2")
{
obj.Code = "2";
obj.Msg = GlobalConst.strUpdateSuccess;
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strRecordExists + "');", true);
//btnCancelProject_Click(sender, e);
}
else
{
obj.Code = "0";
obj.Msg = GlobalConst.strUpdateFaliure;
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strUpdateFaliure + "');", true);
//btnCancelProject_Click(sender, e);
}
}
}
catch (Exception ex)
{
var myActualType = typeof(ProjectMaster);
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strErrorMessge + "');", true);
SecurLog.ErrorLogInfoSave(DateTime.Now, Convert.ToString(HttpContext.Current.Session["WuserCode"]), ex.Source, myActualType.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, "1", ex.Message, ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')), "1", HttpContext.Current.Request.Url.AbsoluteUri, "SECUR", Convert.ToString(HttpContext.Current.Session["ServiceCo"]));
SecurLog.SendErrorMail(DateTime.Now, Convert.ToString(HttpContext.Current.Session["WuserCode"]), ex.Source, myActualType.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, "1", ex.Message, ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')), "1", HttpContext.Current.Request.Url.AbsoluteUri, "SECUR", Convert.ToString(HttpContext.Current.Session["ServiceCo"]));
obj.Code = "0";
obj.Msg = ex.Message;
}
return JsonConvert.SerializeObject(obj);
}
In the above code a mentioned javascript function and C# webmethod the ajax call is not working, not showing any errors and not hitting the break point. please help me thanks in advance!!!!!!!!!!!!!
But the above is working with 5 parameters but not working and not showing any errors where more than 10 parameters is passed to ajax call
please help me..........
Thanks in advance

Can you please add model for the query string params
public class ProjectModel
{
public int Id { get; set; }
public string CompanyCode { get; set; }
public string ProjectName { get; set; }
public string ProjectDescription { get; set; }
public string ProjectType { get; set; }
public string LocationSite { get; set; }
public string Client { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string Status { get; set; }
public string FirstLevelApprover { get; set; }
public string SecondLevelApprover { get; set; }
public string ThirdLevelApprover { get; set; }
public string userComment { get; set; }
public string CrudType { get; set; }
}
and pass model in action method
[WebMethod]
public static string SaveAndUpdateProject(ProjectModel model)
{
// your business logic
// you can access model properties by model.Id, model.CompanyCode
}
Also, in ajax method, you need to change your obj object
var model= new Object();
model.Id = $('#HdxtProjectId').val();
model.CompanyCode = $('#ddlCompanyPrm').val();
model.ProjectName = $('#txtProjectnamePrm').val();
// rest of the properties
And in Ajax method, update data to :
data: JSON.stringify(model),

Related

Why function call twice in ASP.NET Web app

I have a master and content page and I have created an eventhandler on a master page that runs through the content page. And it calls twice. Why i dont understand so please help. even i have handled proper postback
When i call function sendmail() it is calling multiple time. please help where i am going to wrong
Master Page Code
namespace Report_Server
{
public partial class ssrs : System.Web.UI.MasterPage
{
public delegate string NoArgEventHandler(string mailid);
public static event NoArgEventHandler sendMail ;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
mailLabel.Visible = false;
mailaddress.Visible = true;
btnSendMail.Enabled = true;
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mailModal", "$('#mailModal').modal();", true);
//upModal.Update();
}
protected void btnSendMail_Click(object sender, EventArgs e)
{
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mailModal", "$('#mailModal').modal('hide');", true);
mailLabel.Visible = true;
mailaddress.Visible = false;
btnSendMail.Enabled = false;
mailLabel.Text = "Sending, Please Wait";
string message = sendMail(mailaddress.Text);
mailLabel.Text = message;
//Type cstype = this.GetType();
//// Get a ClientScriptManager reference from the Page class.
//ClientScriptManager cs = Page.ClientScript;
//// Check to see if the startup script is already registered.
//if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
//{
// String cstext = string.Format("alert('{0}');",message);
// cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
//}
//string display = "Message Pop-up!";
//ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
}
}
}
Content Page code
namespace Report_Server.Reports.Vouchers.Pages
{
public partial class Sales_Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ssrs.sendMail += new ssrs.NoArgEventHandler(sendmail);
ReportViewer ReportViewer1 = (ReportViewer)this.Master.FindControl("ReportViewer1");
ReportViewer1.LocalReport.ReportPath = "Reports/Vouchers/Reports/Sale_Invoice_2.rdlc";
var dc = new dsserp.reportlib.Vouchers();
var mst = new dsserp.reportlib.Masters();
TextBox mailaddress = (TextBox)Page.Master.FindControl("mailaddress");
getParams();
try
{
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.DataSources.Clear();
requestparam.bill = dc.getSalesInvoice(requestparam.sdt, requestparam.edt, requestparam.dist_id, requestparam.acc_code, requestparam.from_no, requestparam.to_no, requestparam.page_no, requestparam.so_code);
if (mailaddress != null)
mailaddress.Text = requestparam.bill[0].d_email;
requestparam.branch = mst.getBranch();
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = requestparam.bill;
ReportViewer1.LocalReport.DataSources.Add(rds);
ReportDataSource rd2 = new ReportDataSource();
rd2.Name = "DataSet2";
rd2.Value = requestparam.branch;
ReportViewer1.LocalReport.DataSources.Add(rd2);
ReportParameter[] p = new ReportParameter[13];
p[0] = new ReportParameter("firm_id", requestparam.firm_id.ToString());
p[1] = new ReportParameter("branch_id", requestparam.branch_id);
p[2] = new ReportParameter("div_id", requestparam.div_id);
p[3] = new ReportParameter("sdt", requestparam.sdt.ToShortDateString());
p[4] = new ReportParameter("edt", requestparam.edt.ToShortDateString());
p[5] = new ReportParameter("dist_id", requestparam.dist_id == null ? "null" : requestparam.dist_id.ToString());
p[6] = new ReportParameter("acc_code", requestparam.acc_code == null ? "null" : requestparam.acc_code.ToString());
p[7] = new ReportParameter("from_no", string.IsNullOrEmpty(requestparam.from_no) ? "null" : requestparam.from_no);
p[8] = new ReportParameter("to_no", string.IsNullOrEmpty(requestparam.to_no) ? "null" : requestparam.to_no);
p[9] = new ReportParameter("page", requestparam.page_no == null ? "-1" : requestparam.page_no.ToString());
p[10] = new ReportParameter("ismail", "2");
p[11] = new ReportParameter("UserId", requestparam.UserId);
p[12] = new ReportParameter("so_code", requestparam.so_code == null ? "null" : requestparam.so_code.ToString());
ReportViewer1.LocalReport.SetParameters(p);
ReportViewer1.LocalReport.Refresh();
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.InnerException);
}
}
}
protected string sendmail(string mailid)
{
if (requestparam.mailSent == false)
{
string message = "Somthing Went Wrong";
var mailViewer1 = new ReportViewer();
mailViewer1.LocalReport.ReportPath = "Reports\\Vouchers\\Reports\\Sale_Invoice_2.rdlc";
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = requestparam.bill;
mailViewer1.LocalReport.DataSources.Add(rds);
ReportDataSource rd2 = new ReportDataSource();
rd2.Name = "DataSet2";
rd2.Value = requestparam.branch;
mailViewer1.LocalReport.DataSources.Add(rd2);
ReportParameter[] p = new ReportParameter[13];
p[0] = new ReportParameter("firm_id", requestparam.firm_id.ToString());
p[1] = new ReportParameter("branch_id", requestparam.branch_id);
p[2] = new ReportParameter("div_id", requestparam.div_id);
p[3] = new ReportParameter("sdt", requestparam.sdt.ToShortDateString());
p[4] = new ReportParameter("edt", requestparam.edt.ToShortDateString());
p[5] = new ReportParameter("dist_id", requestparam.dist_id == null ? "null" : requestparam.dist_id.ToString());
p[6] = new ReportParameter("acc_code", requestparam.acc_code == null ? "null" : requestparam.acc_code.ToString());
p[7] = new ReportParameter("from_no", string.IsNullOrEmpty(requestparam.from_no) ? "null" : requestparam.from_no);
p[8] = new ReportParameter("to_no", string.IsNullOrEmpty(requestparam.to_no) ? "null" : requestparam.to_no);
p[9] = new ReportParameter("page", "1");
p[10] = new ReportParameter("ismail", "1");
p[11] = new ReportParameter("UserId", requestparam.UserId);
p[12] = new ReportParameter("so_code", requestparam.so_code == null ? "null" : requestparam.so_code.ToString());
//TextBox mailaddress = (TextBox)Page.Master.FindControl("mailaddress");
//Label mailLabel = (Label)Page.Master.FindControl("mailLabel");
message = "Something Went Wrong";
bool smtpFound = false;
var mst = new dsserp.reportlib.Masters();
var Branch = requestparam.branch[0];
smptuser user = new smptuser();
try
{
user.displayName = Branch.smtp_displyname;
user.hostName = Branch.smtp_host;
user.userId = Branch.smtp_UserId;
user.Password = password.DecryptPass(Branch.smtp_Password);
user.mailAddress = Branch.smtp_mailAddress;
user.Port = Convert.ToInt32(Branch.smtp_port);
if (user.Port > 0)
smtpFound = true;
if (smtpFound)
{
var emailFound = string.IsNullOrEmpty(mailid) == false;
if (emailFound)
{
string filename = requestparam.from_no;
if (requestparam.from_no != requestparam.to_no)
{
filename = filename + "-" + requestparam.to_no;
}
string body = "Dear Sir/Maa'm" + "\r\n" + "\r\n" + "A copy of the invoice " + filename + " has been attached for your reference.";
var _file = Path.Combine(Path.GetTempPath(), filename + ".pdf");
export export = new export();
mailViewer1.LocalReport.SetParameters(p);
export.toFile(mailViewer1.LocalReport, _file);
message = mail.send(_file, mailid, "Invoice No:" + filename, body, user); //"Success:sent"
}
else
message = " Email Address Not Found, Please try again";
}
else
message = "No SMTP Server Found";
}
catch (Exception ex)
{
message = "No SMTP Server Found";
}
if (message == "sent")
message = "Successfuly mail sent";
requestparam.response= message;
}
return requestparam.response;
}
public void getParams()
{
string conn = ConfigurationManager.ConnectionStrings["ReportServerEntities"].ConnectionString;
requestparam.firm_id = Convert.ToInt32(Request.QueryString["firm_id"]);
requestparam.branch_id = Request.QueryString["branch_id"];
requestparam.div_id = Request.QueryString["div_id"];
requestparam.sdt = Convert.ToDateTime(Request.QueryString["sdt"]);
requestparam.edt = Convert.ToDateTime(Request.QueryString["edt"]);
requestparam.dist_id = null;
if (!string.IsNullOrEmpty(Request.QueryString["dist_id"]))
requestparam.dist_id = Convert.ToInt32(Request.QueryString["dist_id"]);
requestparam.acc_code = null;
if (!string.IsNullOrEmpty(Request.QueryString["acc_code"]))
requestparam.acc_code = Convert.ToInt32(Request.QueryString["acc_code"]);
requestparam.from_no = Request.QueryString["from_no"];
requestparam.to_no = Request.QueryString["to_no"];
requestparam.UserId = Request.QueryString["User"];
requestparam.page_no = null;
if (!string.IsNullOrEmpty(Request.QueryString["page_no"]))
requestparam.page_no = Convert.ToInt32(Request.QueryString["page_no"]);
requestparam.so_code = null;
if (!string.IsNullOrEmpty(Request.QueryString["so_code"]))
requestparam.so_code = Convert.ToInt32(Request.QueryString["so_code"]);
properties.connectionstring = conn;
properties.firm_id = requestparam.firm_id;
properties.branch_id = requestparam.branch_id;
properties.div_id = requestparam.div_id;
}
public static class requestparam
{
public static int firm_id { get; set; }
public static string branch_id { get; set; }
public static string div_id { get; set; }
public static string from_no { get; set; }
public static string to_no { get; set; }
public static string UserId { get; set; }
public static DateTime sdt { get; set; }
public static DateTime edt { get; set; }
public static int? dist_id { get; set; }
public static int? acc_code { get; set; }
public static int? page_no { get; set; }
public static int? so_code { get; set; }
public static int? ismail { get; set; }
public static List<Voucher.salesInvoice> bill { get; set; }
public static List<Master.Branch> branch { get; set; }
public static bool mailSent { get; set; }
public static string response { get; set; }
}
}
}

Getting the result from controller but ajax call fetching error instead of success in MVC5 and C#

The controller is giving me the result and TempData["DCFormList"] is showing the count 3 (key, value and success message) but in the AJAX call I am getting alert("fail").
public ActionResult INTImportData()
{
if (Session["UserLogon"] != null)
{
BLINTForms objForm = new BLINTForms();
objDCFormList = new DCFormList();
int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
ViewBag.jobId = jobId;
objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
TempData["DCFormList"] = objDCFormList.Form;
return View(objDCFormList.Form);
}
else
return Redirect("~/Account/Login");
}
function GetINTFormTempData(JobId) {
var result = null;
$.ajax({
type: "GET",
url: '/ImportForms/GetINTFormTempDataByJobId',
data: { jobId: JobId },
traditional: false,
success: function (data)
{
result = data;
alert ("JobId");
LoadINTData(result);
if (result.length > 0)
$(".upload").show();
else
$(".upload").hide();
},
error: function (data)
{
alert("fail");
Success = false;
}
});
public List<DCForm> GetINTFormTempDataByJobId(int jobId)
{
objDatabaseHelper = new DatabaseHelper();
List<DCForm> objDCFormList = new List<DCForm>();
DCForm objDCForm;
int record = 0;
try
{
objDatabaseHelper.AddParameter("Job_ID", jobId == 0 ? DBNull.Value : (object)jobId);
DbDataReader reader = objDatabaseHelper.ExecuteReader(BLDBRoutines.SP_GETINTFORMTEMPDATA, CommandType.StoredProcedure);
if (reader.HasRows)
{
while (reader.Read())
{
objDCForm = new DCForm();
objDCForm.SerialNo = ++record;
objDCForm.PayerId = reader.IsDBNull(reader.GetOrdinal("PayerId")) ? 0 : reader.GetInt32(reader.GetOrdinal("PayerId"));
objDCFormList.Add(objDCForm);
}
}
return objDCFormList;
}
catch (Exception exce)
{
throw exce;
}
finally
{
if (objDatabaseHelper != null)
objDatabaseHelper.Dispose();
}
}
public class DCForm : DataOperationResponse
{
public int SerialNo { get; set; }
public int PayerId { get; set; }
public class DCFormList : DataOperationResponse
{
private List<DCForm> _form = null;
public DCFormList()
{
if (_form == null)
_form = new List<DCForm>();
}
public List<DCForm> Form
{
get { return _form; }
set { _form = value; }
}
}
I have just tried to reproduce your case. Here are sample code. You can update your code to get from Database from my code.
Your controller:
public class ImportFormsController : Controller
{
public JsonResult INTImportData(int jobId)
{
//if (Session["UserLogon"] != null)
//{
BLINTForms objForm = new BLINTForms();
var objDCFormList = new DCForm.DCFormList();
//int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
//ViewBag.jobId = jobId;
objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
//TempData["DCFormList"] = objDCFormList.Form;
//Response.StatusCode = (int)HttpStatusCode.OK;
return Json(objDCFormList.Form, JsonRequestBehavior.AllowGet);
//}
//else
//return Json("Login required", JsonRequestBehavior.AllowGet);
}
}
public class BLINTForms
{
public List<DCForm> GetINTFormTempDataByJobId(int jobId)
{
List<DCForm> objDCFormList = new List<DCForm>();
DCForm objDCForm;
int record = 0;
try
{
for (var i = 0; i < 5; i++)
{
objDCForm = new DCForm();
objDCForm.SerialNo = ++record;
objDCForm.PayerId = 100;
objDCFormList.Add(objDCForm);
}
return objDCFormList;
}
catch (Exception exce)
{
throw exce;
}
finally
{
}
}
}
public class DCForm : DataOperationResponse
{
public int SerialNo { get; set; }
public int PayerId { get; set; }
public class DCFormList : DataOperationResponse
{
private List<DCForm> _form = null;
public DCFormList()
{
if (_form == null)
_form = new List<DCForm>();
}
public List<DCForm> Form
{
get { return _form; }
set { _form = value; }
}
}
}
public class DataOperationResponse
{
//public string Message { get; set; }
}
I create a test in HomeController:Index with Index.cshtml
<input type="text" id="jobId"/>
<button onclick="GetINTFormTempData($('#jobId').val())">Get Data</button>
<script>
function GetINTFormTempData(JobId) {
var result = null;
$.ajax({
type: "GET",
url: '/ImportForms/INTImportData', //**change url**
data: { jobId: JobId },
traditional: false,
success: function(data) {
result = data;
alert("JobId");
alert(JSON.stringify(data));
LoadINTData(result);
if (result.length > 0)
$(".upload").show();
else
$(".upload").hide();
},
error: function(data) {
alert("fail");
Success = false;
}
});
}
</script>
You should use this
Change ActionResult to JsonResult and
return Json(objDCFormList.Form, JsonRequestBehavior.AllowGet);
TempData["DCFormList"] can not get value in your AJAX call.
And also check your url in route with url in ajax call.
If I get your question correctly and, and if you want to use ActionResult set result as Success with:
Response.StatusCode = (int)HttpStatusCode.OK;
So in your case:
public ActionResult INTImportData()
{
if (Session["UserLogon"] != null)
{
BLINTForms objForm = new BLINTForms();
objDCFormList = new DCFormList();
int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
ViewBag.jobId = jobId;
objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
TempData["DCFormList"] = objDCFormList.Form;
Response.StatusCode = (int)HttpStatusCode.OK;
return View(objDCFormList.Form);
}
else
return Redirect("~/Account/Login");
}
I hope this helps.

object makes web method loop

If I delete this value = new { token = 1 } or convert to value = "" webmethod works fine, otherwise method get triggered after return repeatedly.
Why this happens how to solve?
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "login/{username}/{password}")]
public Result Login(string username, string password)
{
somecode..
if (user != null && user.Password == password)
{
return new Result { statusCode = "200", message = "Success", value = new { token = 1 } };
}
else
{
return new Result { statusCode = "401", message = "Fail", value = "" };
}
}
public class Result
{
public string statusCode { get; set; }
public string message { get; set; }
public object value { get; set; }
}
this didn't work too;
return new Result { statusCode = "200", message = "Success", value = new Token { token = "some string" } }
Try Like This
public Result Login(string username, string password)
{
int token=1;
Result response = new Result();
if (user != null && user.Password == password)
{
response.message = "Success";
response.statusCode = "200";
response.value = token;
}
else
{
response.message = "Fail";
response.statusCode = "401";
response.value = null;
}
return response;
}
public class Result
{
public string statusCode { get; set; }
public string message { get; set; }
public object value { get; set; }
}

Without use Report Viewer RDLC Supreport Loading error

I have RDLC report which has sup report. When I use report viewer then system works fine. But when I want to load report without report viewer then system returns error. Please help me in this point. Thanks
public void DetailsReport()
{
string mimeType;
byte[] renderedBytes;
string reportPath = "rptAllEmployees.rdlc";//report path
string datasetName = "my";//report datasource
decimal reportWidth = 11.5m;
decimal reportHeight = 8.5m;
PopulateReport( CustomDS.GetAllEmployees(), datasetName, reportPath, out mimeType, out renderedBytes, reportWidth, reportHeight);
//return File(renderedBytes, mimeType);
}
private void PopulateReport(List<Employee> objectList, string datasetName, string reportPath, out string mimeType, out byte[] renderedBytes, decimal fileWidth, decimal fileHeight)
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath(reportPath);
ReportDataSource reportDataSource = new ReportDataSource(datasetName, objectList);
localReport.SubreportProcessing +=
new Microsoft.Reporting.WebForms.SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
localReport.DataSources.Add(reportDataSource);
//localReport.SetParameters(new ReportParameter("pm", "", false));
string reportType = "PDF";
mimeType = string.Empty;
string encoding = string.Empty;
string fileNameExtension = string.Empty;
//The DeviceInfo settings should be changed based on the reportType
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>" + fileWidth + "in</PageWidth>" +
" <PageHeight>" + fileHeight + "in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
//Render the report
//Eror occured in this point
**renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);**
//Clear the response stream and write the bytes to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=foo." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
void LocalReport_SubreportProcessing(
object sender,
Microsoft.Reporting.WebForms.SubreportProcessingEventArgs e)
{
// get empID from the parameters
int iEmpID = Convert.ToInt32(e.Parameters[0].Values[0]);
// remove all previously attached Datasources, since we want to attach a
// new one
e.DataSources.Clear();
// Retrieve employeeFamily list based on EmpID
var employeeFamily = CpReportCustomData.Data.CustomDS.GetAllEmployeeFamily()
.FindAll(element => element.ID == iEmpID);
// add retrieved dataset or you can call it list to data source
e.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource()
{
Name = "DSEmployeeFamily",
Value = employeeFamily
});
}
public class CustomDS
{
private static List<Employee> _lstEmployee = null;
public static List<Employee> GetAllEmployees()
{
if (_lstEmployee == null)
{
_lstEmployee = new List<Employee>();
_lstEmployee.Add( new Employee()
{
ID=1,
Name="Alok",
Age=30
});
_lstEmployee.Add(new Employee()
{
ID = 2,
Name = "Ashish",
Age = 30
});
_lstEmployee.Add(new Employee()
{
ID = 3,
Name = "Jasdeep",
Age = 30
});
_lstEmployee.Add(new Employee()
{
ID = 4,
Name = "Kamlesh",
Age = 31
});
}
return _lstEmployee;
}
private static List<EmployeeFamily> _lstEmployeeFamily = null;
public static List<EmployeeFamily> GetAllEmployeeFamily()
{
if (_lstEmployeeFamily == null)
{
_lstEmployeeFamily = new List<EmployeeFamily>();
_lstEmployeeFamily.Add(new EmployeeFamily()
{
ID = 1,
Name = "AlokWife",
Relation = "Wife"
});
_lstEmployeeFamily.Add(new EmployeeFamily()
{
ID = 1,
Name = "AlokDaughter",
Relation = "Daughter"
});
_lstEmployeeFamily.Add(new EmployeeFamily()
{
ID = 2,
Name = "AshishWife",
Relation = "Wife"
});
_lstEmployeeFamily.Add(new EmployeeFamily()
{
ID = 3,
Name = "JasdeepFather",
Relation = "Father"
});
_lstEmployeeFamily.Add(new EmployeeFamily()
{
ID = 3,
Name = "JasdeepMother",
Relation = "Mother"
});
_lstEmployeeFamily.Add(new EmployeeFamily()
{
ID = 4,
Name = "KamleshWife",
Relation = "Wife"
});
_lstEmployeeFamily.Add(new EmployeeFamily()
{
ID = 4,
Name = "KamleshDaughter",
Relation = "Daughter"
});
}
return _lstEmployeeFamily;
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class EmployeeFamily
{
public int ID { get; set; }
public String Name { get; set; }
public string Relation { get; set; }
}

Convert JSON data to querystring in C# GET request

What is the best way to convert a JSON object into querystrings to append to a GET Url? The POST is straight forward and gets read by my Web API backend.
{Name: 'Mike' } = ?Name=Mike
private static string MakeRequest(HttpWebRequest req, string data)
{
try
{
if (req.Method == Verbs.POST.ToString() || req.Method == Verbs.PUT.ToString() || req.Method == Verbs.DELETE.ToString())
{
var encodedData = Encoding.UTF8.GetBytes(data);
req.ContentLength = encodedData.Length;
req.ContentType = "application/json";
req.GetRequestStream().Write(encodedData, 0, encodedData.Length);
}
using (var response = req.GetResponse() as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
catch (WebException we)
{
if(we.Response == null)
{
return JsonConvert.SerializeObject(new { Errors = new List<ApiError> { new ApiError(11, "API is currently unavailable") }});
}
using (var response = we.Response as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
If the json object is flat as in your example, then
string json = #"{
""name"": ""charlie"",
""num"": 123
}";
var jObj = (JObject)JsonConvert.DeserializeObject(json);
var query = String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp=>jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));
query would be name=charlie&num=123
I make this code to run in .Net Core:
public static string JsonToQuery(this string jsonQuery)
{
string str = "?";
str += jsonQuery.Replace(":", "=").Replace("{","").
Replace("}", "").Replace(",","&").
Replace("\"", "");
return str;
}
Example:
var _baseURI = "http://www.example.com/";
var endPoint = "myendpoint";
ExampleObjectModel requestModel = new ExampleObjectModel();
var requestModelJson = JsonConvert.SerializeObject(requestModel);
var url = string.Format("{0}{1}{2}", _baseURI, endPoint, requestModelJson.JsonToQuery());
Try this, work all object, in deep
public static class ExtensionMethods
{
public static string GetQueryString(this object obj, string prefix = "")
{
var query = "";
try
{
var vQueryString = (JsonConvert.SerializeObject(obj));
var jObj = (JObject)JsonConvert.DeserializeObject(vQueryString);
query = String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp =>
{
if (jp.Value.Type == JTokenType.Array)
{
var count = 0;
var arrValue = String.Join("&", jp.Value.ToList().Select<JToken, string>(p =>
{
var tmp = JsonConvert.DeserializeObject(p.ToString()).GetQueryString(jp.Name + HttpUtility.UrlEncode("[") + count++ + HttpUtility.UrlEncode("]"));
return tmp;
}));
return arrValue;
}
else
return (prefix.Length > 0 ? prefix + HttpUtility.UrlEncode("[") + jp.Name + HttpUtility.UrlEncode("]") : jp.Name) + "=" + HttpUtility.UrlEncode(jp.Value.ToString());
}
)) ?? "";
}
catch (Exception ex)
{
}
return query;
}
}
To use: SomeObject.GetQueryString();
if your object(Entity) have a Children like this Entity :
public class Parent
{
public Child childs { get; set; } = new Child();
public int PageIndex { get; set; }
public int? PageSize { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
}
Your Can Use This Code For Build Query:
First Convert You Enrity Model To JObject
And Call This Method :
public static string GetQueryString(this JObject jObj)
{
return String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp =>
{
if (jp.Value.Type == JTokenType.Object)
{
var arrValue = String.Join("&",
jObj.Values().Children().Cast<JProperty>()
.Select(jp => jp.Path + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));
return arrValue;
}
else
{
var arrValue = String.Join("&", jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString()));
return arrValue;
}
}
)) ?? "";
}
Your Can Get Like This QueryString :
childs.Id=1&childs.Name="Test"&PageIndex=1&PageSize=1

Categories