简体   繁体   中英

How to call a sql function inside a javascript file? asp.net c#

I'm developing a calendar which takes entries from a sql database. Inside the javascript file the calendar is builded programatically and I hardcoded the code when it generates the calendar cell within the day(in this case is the var counter), I just need to put the query inside the function

JavaScript File

  if (counter == 2 //2 is the Harcoded day
        && mes == 8 //Hardcoded month
        && anio == 2014) { //Harcoded year
            PageMethods.Msg(onSuccess);
            function onSuccess(response) {
                alert(response);
            }

            htmlContent += "<div class='usuer'>Here data retrieved from DB</div>";
            htmlContent += "<div class='client'>Here data retrieved from DB</div>";
            htmlContent += "<div class='num'>Here data retrieved from DB</div>";
            htmlContent += "<div class='status'></div>";
        }

I create the method in the Code Behind but I dont know how to pass the Object Div to get the result of the query and set it in the Divs OR get the counter to put it in the query and get the the results of the specific days

Code Behind

[System.Web.Services.WebMethod]
    public static string Msg()
    {
        return "Hello world";


        string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        using (SqlConnection myConnection = new SqlConnection(connStr))
        {
            myConnection.Open();
            SqlCommand sqlCommand = new SqlCommand(" SELECT * FROM table",myConnection);


            //Add parameters to the query
            //<--- Here? How to get counter of the javascript file? :( 


            SqlDataReader dr = sqlCommand.ExecuteReader();
            if (dr != null)
            {
                while (dr.Read())
                {
                    //<-- Here? How to set the result to the divs? :(

                }
            }
        }
    }

Better use Ajax request to load data to your calendar but if you must

create a action where you prepare your data and sent it as parameter to view. In view use <script> tags end place here your code.

Example

acction

    public ActionResult MyJS()
    {
        calendar = new List<DateTime>();

        calendar.Add(DateTime.Parse("2010-03-21 12:00"));
        calendar.Add(DateTime.Parse("2011-03-21 12:00"));
        calendar.Add(DateTime.Parse("2012-03-21 12:00"));

        return View(calendar);
    }

viev

@model List<DateTime>
@{
    Layout = null; // important
}
@foreach (var item in Model)
{
    <text> 
        alert(" @item.ToString()  ");
    </text>
}

and add to layout <script src="home/myjs"></script>

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