asp.net in OpenFileDialog - asp.net

I am creating a web server through asp.net.
The source works well in debug mode.
However, after posting to iis, if you go through the source, you will get the error 'HTTP Error 503. The service is unavailable' after about 20 seconds.
I am confident that there is an error in the OpenFileDialog section.
In the past, this code worked well after posting. I do not know what has been modified since then.
Thanks in advance for your help.
.js code
action: function (e, dt, node, config) {
$.ajax({
"url": "/api/Member/ExcelRead",
"type": "POST",
"datatype": 'json',
success: function (data) {
if (data === 'OK') {
alert("성공");
}
},
error: function (response, state, errorCode) {
alert("실패");
}
});
.cs
public class MemberController : ApiController
{
[HttpPost]
public string ExcelRead()
{
ExcelHelper helper = new ExcelHelper();
Thread th = new Thread(helper.ReadExcelData);
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
if (helper.data == null)
return ("NO");
return ("OK");
}
}
public void ReadExcelData()
{
IsRun = false;
OpenFileDialog openFile = new OpenFileDialog();
openFile.DefaultExt = "xlsx";
openFile.Filter = "Excel Files(*.xlsx)|*.xlsx";
DialogResult dresult = openFile.ShowDialog();
if (dresult != DialogResult.OK)
{
return;
}
if (openFile.FileNames.Length > 0)
{
foreach (string filename in openFile.FileNames)
{
//this.textBox1.Text = filename;
}
}
}

Related

my action method returning {"success=true,message="work done"} ASP.net MVC 5

Here is my create action method. I want get alert form it when success is true.
public JsonResult Create(Student student ,HttpPostedFileBase img)
{
if (ModelState.IsValid)
{
if (img !=null)
{
var name = Path.GetFileNameWithoutExtension(img.FileName);
var ext = Path.GetExtension(img.FileName);
var filename = name + DateTime.Now.ToString("ddmmyyyff") + ext;
img.SaveAs(Server.MapPath("~/img/"+filename));
student.ImageName = filename;
student.Path = "~/img/" + filename;
}
db.Students.Add(student);
db.SaveChanges();
return Json(new { success = true, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
ViewBag.ClassID = new SelectList(db.Classes, "Id", "Name", student.ClassID);
return new JsonResult { Data = new { success = false, message = "data not saved" } };
}
Here is my ajax function :
function onsub(form) {
$.validations.unobtrusive.parse(form);
if (form.valid()) {
var ajaxConfig = {
type: "POST",
url: form.action,
data: new FormData(form),
success: function (response) {
if (response.success ) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}
}
if ($(form).attr("enctype") == "multipart/form-data") {
ajaxConfig["contentType"] = false;
ajaxConfig["processData"] = false;
}
$.ajax(ajaxConfig);
}
return false;
}
How can I get an alert form it
without reloading the form. I also want to submit images and other files to create an action method.
This is the result that I get after submitting the form:
In your case you are calling Create action which returning the JSON Result and the same Json response is displayed in browser.
Their should be a View page from where you will call this method by using the Ajax call, then you will be able to see your alert message.

Can't pass data to asp.net core

I have a problem, I need to send data from my Angular to my ASP.NET Core server. Here is controller:
[HttpPut]
public IActionResult setCoupon(int id, string CouponCode, int DiscountPercent)
{
try
{
var coupon = new Coupon()
{
Id = id,
CouponCode = CouponCode,
DiscountPercent = DiscountPercent
};
return Ok(coupon);
}
catch (Exception)
{
return BadRequest("Wystąpił błąd");
}
}
Here is factory from ngResource (getCoupon is working):
app.factory('couponApi',
function($resource) {
return $resource("/coupon/setCoupon",
{},
{
getCoupon: {
method: "GET",
isArray: false
},
putCoupon: {
method: "PUT",
isArray: false,
}
});
});
Here is usage of factory:
$scope.addCouponCode = function(coupon) {
couponApi.putCoupon(coupon);
};
When i debug my asp.net server i found my params null or 0. I have the same problem on restangular library.
I also try this way to write controller method
[HttpPut]
public IActionResult setCoupon(Coupon coupon)
{
try
{
return Ok(coupon);
}
catch (Exception)
{
return BadRequest("Wystąpił błąd");
}
}
My json which I try to send is this
{"id":1,"couponCode":"abc","discountPercent":10}
and my Echo method send me this:
{"id":0,"couponCode":null,"discountPercent":0}
Update
Apparently in asp.net core, method need to have attribute[FromBody]
[HttpPut]
public IActionResult setCoupon([FromBody] Coupon coupon)
{
try
{
return Ok(coupon);
}
catch (Exception)
{
return BadRequest(new {errorMessage = "Wystąpił błąd"});
}
}
As Aldo says in the comments. The answer is C# expects case-sensitive matching of the json data. So:
{"id":1,"couponCode":"abc","discountPercent":10}
needs to be:
{"id":1,"CouponCode":"abc","DiscountPercent":10}
You were getting a 0 for 'discountPercent' because that is the default value of the unmatched int, whereas null is the default for a unmatched string, hence Echo returns:
{"id":0,"couponCode":null,"discountPercent":0}

How to return JSON for errors outside the WebApi pipeline?

I'm creating a public-facing API using WebApi 2.1, have a dedicated WebApi project (no MVC), have the API hosted in IIS 7.5 on its own server, and have the design goal of returning only JSON or empty content, and never returning HTML.
I am happily using ExceptionFilterAttribute to deal with exceptions arising within the WebApi pipeline, as follows:
public class GlobalExceptionHandler : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
// Log the exception to Elmah
Elmah.Error error = new Elmah.Error(context.Exception, HttpContext.Current);
error.Detail = ActionState.GetRequestParameters(context) + error.Detail;
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(error);
if (context.Exception is NotImplementedException)
{
context.Response = context.Request.CreateErrorResponse(
HttpStatusCode.NotImplemented
, "The API method has not yet been implemented"
);
}
else
{
context.Response = context.Request.CreateErrorResponse(
HttpStatusCode.InternalServerError
, "A " + context.Exception.GetType().ToString() + " was thrown"
);
}
base.OnException(context);
}
}
The filter is properly added in App_Start:
config.Filters.Add(new SecureVideoApiGlobalExceptionHandler());
The problem comes when an error arises that is outside the WebApi pipeline. For example, a request comes with the URI of the web root, https://mysite.com/, and the response is a 403.11 with an HTML body stating "The Web server is configured to not list the contents of this directory." Another possibility is that there is an error in code called in the Application_Start method of global.asax, for example in the AutoMapper code, which is asserting that all the mappings are valid.
My question is: how can I make it such that when any error occurs on the API server, only a JSON error message is returned, and never an HTML error message?
I have tried
<modules runAllManagedModulesForAllRequests="true">
This allows me to handle any error in Application_Error() in global.asax, but I do not have the ability to access a Response object there to emit JSON.
You can do somthing like this Attribute
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
public class ExceptionActionFilter : ExceptionFilterAttribute
{
private static Logger _log ;//= LogManager.GetLogger("mysite");
public override void OnException(HttpActionExecutedContext contex)
{
if (_log == null)
_log = LogManager.GetCurrentClassLogger();
var ex = contex.Exception;
_log.Error(ex);
contex.Response = contex.Request.CreateResponse(HttpStatusCode.OK,
new
{
ErrorMessage = contex.Exception.Message,
RealStatusCode = (int)(ex is NotImplementedException || ex is ArgumentNullException ? HttpStatusCode.NoContent : HttpStatusCode.BadRequest),
ReturnUrl = CommonContext.ErrorUrl
},
new JsonMediaTypeFormatter());
base.OnException(contex);
}
}
And then put the Attribute on a class exc and on the clien side
or with filter
public class ExceptionLoggerFilter : System.Web.Http.Filters.IExceptionFilter
{
private static Logger _log;
public ExceptionLoggerFilter()
{
if (_log == null)
_log = LogManager.GetCurrentClassLogger();
}
public bool AllowMultiple { get { return true; } }
public System.Threading.Tasks.Task ExecuteExceptionFilterAsync(
System.Web.Http.Filters.HttpActionExecutedContext contex,
System.Threading.CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.Factory.StartNew(() =>
{
_log.Error(contex.Exception);
contex.Response = contex.Request.CreateResponse(HttpStatusCode.OK,
new { RealStatusCode = (int)HttpStatusCode.Forbidden, ReturnUrl = "#/error.html"},
contex.ActionContext.ControllerContext.Configuration.Formatters.JsonFormatter);
}, cancellationToken);
}
}
And then in Global.asax.cs
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
Database.SetInitializer<MySiteContext>(null);
}
and
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)//RouteCollection config)//
{
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Filters.Add(new ExceptionLoggerFilter());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
}
}
And in the client side maybee somthing like
$.controller.ajax.promise = controller.ajax.promise = function ( obj )
{
var deferred = q.defer();
$.ajax( {
type: obj.type || "GET",
url: obj.url,
context: obj.context || null,
data: obj.data || null,
contentType: obj.contentType || "application/json; charset=utf-8",
dataType: obj.dataType || "json",
success: function ( res, textStatus, jqXHR )
{
if ( res.RealStatusCode )
{
switch ( res.RealStatusCode )
{
case 400://x error
res.ClientMessage = res.ErrorMessage;
deferred.reject(res);
break;
case 408://y errors
location.href = res.ReturnUrl;
return false;
case 403://ext
msgbox.alert( {
message: 'Ma belle msg',
title: "Error"
} );
deferred.reject();
location.href = res.ReturnUrl;
return false;
default:
deferred.reject();
location.href = res.ReturnUrl;
break;
}
}
deferred.resolve( res );
return true;
},
error: function ( jqXHR, textStatus, errorThrown )
{
deferred.reject( { msg: jqXHR.statusText, jqXHR: jqXHR, textStatus:textStatus, errorThrown:errorThrown } );
}
} );
return deferred.promise;
};
I hope this helps other googlers out there! (Like #Thomas C. G. de Vilhena said =)

selecting all the records from the database using jquery ajax in asp.net

i want to generate the table of contents from database.. using jquery ajax in asp.net, i am using sql server 2008 as a backend. for this i created a webmethod in my normal aspx page. and on the clientside wrote the ajax script to fetch records but when i loop through the results, i gets message undefined and nothing happens.. i want to generate table out of the records from database below is my webmethod.
[WebMethod]
public static Poll[] GetPollDetailed()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("sp_SelectQuestion", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#siteid", 3);
DataTable dt = new DataTable();
da.Fill(dt);
List<Poll> _poll1 = new List<Poll>();
foreach (DataRow row in dt.Rows)
{
Poll _poll = new Poll();
_poll.QuestionID = Convert.ToInt32(row["questionID"]);
_poll.Question = row["question"].ToString();
_poll.Published = Convert.ToInt32(row["visible"]);
_poll.Date = Convert.ToDateTime(row["Added_Date"]);
}
return _poll1.ToArray();
}
public class Poll
{
public Poll() { }
private int _questionId, _published;
private string _question;
private DateTime _date;
public int QuestionID
{
get { return _questionId; }
set { _questionId = value; }
}
public string Question
{
get { return _question; }
set { _question = value; }
}
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
public int Published
{
get { return _published; }
set { _published = value; }
}
}
</code>
and below is my script.
<code>
$(this).load(function () {
$.ajax({
type: "POST",
url: "AddPollAJax.aspx/GetPollDetailed",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
error: function (data) {
alert("Error: " + data.responseText);
}
});
});
</code>
can any one please help me to resolve this issue, i am very curious about it.
Assuming your service is configured correctly to return JSON data, issue lies at your js code fragment for success callback i.e.
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
MS ASP.NET script services always return a wrapped JSON due to security issues, so you need unwrap resultant JS object to get the actual data. So you need to change the code to
success: function (result) {
var data = result.d; // actual response will be in this property
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
BTW, ASP.NET Web Services are now considered legacy, so I will suggest you to migrate to WCF services instead.

Error messages in ASP.NET with jQuery UI

I've been using my own Error reporting module which was combination of simple c# and jQueryUI Dialog. Problem is that once error or success occurs i do write it's value to session. It does work pretty good on pages with Responce.Redirect on error but not on pages where i catch an error and then return to same form.
My question is why does session which added pre-postback fails to load in pages where i have return statement on some condition.
And if there another way to save errors and success message except in session ? Maybe global variables or something like that ...
CODE EXAMPLES
this is Error class
public static string getMessage()
{
HttpContext c = HttpContext.Current;
string messageType = "";
if (c.Session["errorMessage"] != null)
{
messageType = "errorMessage";
}
else if (c.Session["successMessage"] != null)
{
messageType = "successMessage";
}
if (!string.IsNullOrEmpty(messageType))
{
string[] messageBody = c.Session[messageType].ToString().Split('|');
StringBuilder userMessageSb = new StringBuilder();
userMessageSb.Append(string.Format("<div id=\"{0}\" title=\"{1}\">{2}</div>", messageType, messageBody[0], messageBody[1]));
// fix so message will not re-appear
c.Session.Remove(messageType);
messageType = userMessageSb.ToString();
}
return messageType;
}
public static void setSuccess(string successMessage)
{
HttpContext.Current.Session["successMessage"] = setMessage("success", successMessage);
}
public static void setError(string errorMessage)
{
HttpContext.Current.Session["errorMessage"] = setMessage("error", errorMessage);
}
private static string setMessage(string messageTitle, string messageBody)
{
return string.Format("{0}|{1}", messageTitle, messageBody);
}
i set message like this prior to redirect or return
Errors.setError(my error is");
i get error on bottom of my masterpage like this
<%= Errors.getMessage() %>
and this is JS
$(function () {
$("#errorMessage").dialog("destroy");
$("#successMessage").dialog("destroy");
if ($("#errorMessage").length != 0) {
$("#errorMessage").dialog({
modal: true,
height: 300,
width: 400,
buttons: {
Ok: function () {
$(this).dialog('close');
}
}
});
}
if ($("#successMessage").length != 0) {
$("#successMessage").dialog({
modal: true,
height: 300,
width: 400,
buttons: {
Ok: function () {
$(this).dialog('close');
}
}
});
}
});
There is a possibility that <%= Errors.getMessage() %> executes before you call Errors.setError(my error is") in case when you are not redirecting.
Hope below answer helps.
Create a property in your master page code behind
public string MessagePlaceholder
{
get { return messagePlaceholder.InnerHtml; }
set { messagePlaceholder.InnerHtml = value; }
}
Replace <%= Errors.getMessage() %> with a div place holder like below
<div id="messagePlaceholder" runat="server"></div>
And here is your setError method
public static void setError(string errorMessage, bool redirecting)
{
HttpContext.Current.Session["errorMessage"] = setMessage("error", errorMessage);
if (!redirecting)
{
((HttpContext.Current.Handler as System.Web.UI.Page).Master as YourMasterPageType).MessagePlaceholder = getMessage();
}
}
EDIT
Sorry I forgot this
In Page_Load event of your master page
if(!IsPostBack)
{
messagePlaceholder.InnerHtml = Errors.getMessage();
}

Resources