简体   繁体   中英

Error converting string to int32

The following method works:

[System.Web.Services.WebMethod]
public string GetData(string year)
{
    Int32 iYear = DateTime.Now.Year;
    if (DateTime.IsLeapYear(iYear))
    {
        return "true";
    } else
    {
        return "false";
    }
}

But if I pass a year say 2015 as a string, the following code doesn't work.

using System;

public partial class _Default : System.Web.UI.Page
{
public string output = "";
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Params["callback"] != null)
    {
        output = Request.Params["callback"] + "('" + GetData(Request.Params["year"]) + "')";
    }
}

[System.Web.Services.WebMethod]
public string GetData(string year)
{
    int iYear = Convert.ToInt32(year);

    if (DateTime.IsLeapYear(iYear))
    {
        return "true";
    } else {
        return "false";
    }
}
}

I'm having a hard time figuring out my mistake. I'm passing year as a string to an jQuery Ajax call.

Any ideas why?

Joe

Found the error, the error was in the Ajax call, I was enclosing the date in quotes. Thanks all for your support and help.

This is what I had data: { year: "' + $('#txtYear').val() + '"}

When I removed quotes, it worked. data: { year: +$('#txtYear').val() }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM