jQuery和ASP.NET

介绍

在ASP.NET中使用jQuery并不那么复杂。 只需按照以下步骤操作,您就可以在这里实现我们的主要目标。 使用下面的HTML代码包含jQuery。

 
 

或者,您可以像这样使用ASP.NET服务器端代码:

protected override void Render(HtmlTextWriter writer)
{
    this.Page.ClientScript.RegisterClientScriptInclude("jQuery", "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");
    base.Render(writer);
}

为了在页面加载时执行任何功能,ASP.NET具有内置方法来注册启动脚本。 下面的代码将在页面加载时运行javascript函数“ helloWorld”,该函数会附加文本“ Hello World!”。 内部div,其ID为“ divSample”



    jQuery with asp.net examples - HelloWorld with jQuery

    

C#服务器代码:

protected override void Render(HtmlTextWriter writer)
{
    this.Page.ClientScript.RegisterClientScriptInclude("jQuery",
        "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");
    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(),
        "startup", "

现在,您已经有了关于如何将jQuery放入ASP.NET页面并在页面加载时运行脚本的想法。
我们将看到如何使用jQuery将数据传递到服务器并动态地获取响应。

jQuery选择器

这是jQuery中最有用的功能。 这有助于选择HTML文档中的元素。
jQuey有很多选择器选项,您可以通过其ID,年龄名称,类名称以及特定属性来选择一个元素或元素数组。
有用的选择器示例:

$("#selectDiv") //will return an array containing element which has id = selectDiv

$("div") //will return an array containing all "div" elements.

$(".header") //will return an array containing elements which has class name = header

$("input[name='emailaddress']") //will return an array containing "input" elements which has name = emailaddress

jQuery可链接性

在jQuery中,使代码简明扼要是一个很棒的概念。 在每个jQuery方法中,它都会返回查询对象本身,因此将允许对其执行功能并维护链。
例:

$("div").addClass("sample").html("html changed").show();

jQuery对象访问器

可以将其用于任何jQuery选择器返回的对象。
例:

$(". removeItem").each{function()
{
    $(this).bind("click",
        return confirm("Are you sure you wish to delete this item?"));
}

jQuery事件

例:

$("p").bind("click", function()
{
  $(this).append("clicked");
});
function clickMe()
{
    $("#debugDiv").append("clicked!");
}

$("p").bind("click",clickMe); // Will bind clickMe function on click event of paragraphs

$("p").unbind("click",clickMe); // Will unbind clickMe function on click event of paragraphs
$(document).ready(function()
{
   $("p").append("This text appended on DOM ready");
});

使用jQuery和ASP.NET的Ajax

使用jQuery的Ajax并不难实现。 有一些选项可以使用jQuery Ajax从服务器获取异步回复。
“加载”方法是jQuery Ajax的最简单形式。
例:

$("#serverResponse").load("AjaxCall.aspx"); // Response from page AjaxCall.aspx will get loaded in
// Div "serverResponse" Send data to the server using jQuery Ajax Example:

$.get("AjaxCall.aspx" // Call page AjaxCall.aspx
,{name: $("#txtName").val()} //Pass querystring "name" with value of text box "txtName"
,function(data) // On successfully retrival of response
{
      $("#serverResponseSendData").html(data); // Apply recevied html response to html of div "serverResponseSendData"
});

带有JSON数据的jQuery Ajax

Javascript Object Notation或JSON是在Ajax调用中传输的一种很好的数据形式。

public static string datatableToJSON(DataTable dt)
{
    StringBuilder jsonStringBuilder = new StringBuilder();
    StringWriter jsonStringWriter = new StringWriter(jsonStringBuilder);

    JsonWriter jsonWriter = new JsonTextWriter(jsonStringWriter);

    if (dt != null && dt.Rows.Count > 0)
    {
        jsonWriter.Formatting = Formatting.None;

        jsonWriter.WriteStartArray();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonWriter.WriteStartObject();
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonWriter.WritePropertyName(dt.Columns[j].ColumnName.ToString().ToLower());
                jsonWriter.WriteValue(dt.Rows[i][j].ToString());
            }
            jsonWriter.WriteEndObject();
        }
        jsonWriter.WriteEndArray();

        return jsonStringBuilder.ToString();
    }
    else
    {
        return null;
    }
}
[/js]

Now we’ll try to parse this JSON data and we’ll build a grid out of its data at client side.

[js]
$.ajax({type:"POST", // jQuery ajax with POST method
    url: "JSONCall.aspx", // Call page JSONCall.aspx
    success:function(serverResponseData) // On success call function
    {
        dtItems = eval("(" + serverResponseData + ")"); // evaluate retrived data to javascript object

        var htmlGrid = "";

        htmlGrid += "

Effects with jQuery

jQuery has its built it effects such as show, hide, slideDown and stuffs like that. Effect method has parameter for duration and callback function. This will get called after finishing an animation effect.
Example:

$('#divSample').hide(1000); // will hide the div "divSample", and it will animate for 1000 miliseconds

$('#divSample').show(1000); // will show the div "divSample"

$('#divSample').toggle (1000); // will toggle display of the div "divSample"
$("#divSample3").animate( // will animate the div "divSample"
   // to height 200px, width 400px and opacity of .5, for 1000 milisecond
{height:200, width:400, opacity: .5}, 1000, function()
{
   alert("Animation complete!"); // call method on completion of animation
});

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

💁‍♀️ Fun Fact: Python was ranked #2 on a recent highest paid coders list. *


🤓 Ok. When did a code editor from Microsoft become kinda cool!?

Popular Books

视觉工作室代码端到端针对Web开发人员的编辑和调试工具

Visual Studio Code: End-to-End Editing and Debugging Tools for Web Developers

远程工作的艺术

The Art of Working Remotely

表单设计模式

Form Design Patterns

IndexItem CodePrice
"; for(var i=0;i
"+dtItems[i].index+""+dtItems[i].itemcode+""+dtItems[i].price+"
"; // Build grid from retrived data in current item } htmlGrid += ""; $("#divJSONGrid").html(htmlGrid); // apply created grid HTML to a div "divJSONGrid" } });

From: https://www.sitepoint.com/jquery-asp-net/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值