技术开发 频道

Asp.net MVC简单实用三种使用Ajax方式

  第二种方式:利用Jquery: 在控制器中添加代码IndexJquery方法和AddComment方法的代码,CommentController代码如下所示

public class CommentController : Controller
{
    
private IList<string> _comments = new List<string>();

    
public ActionResult Index()
    {
        return View();
    }

    
public ActionResult IndexJquery()
    {
        return View();
    }

    
public ActionResult AddComment(string comment)
    {
        _comments.Add(
"<li>" + comment + "</li>");
        return Content(
string.Join("\n", _comments.ToArray()));
    }

    
public void AddCommentServer()
    {        
string comment = Request["comment"].ToUpper();

        _comments.Add(
"<li>" + comment + "</li>");

        Response.ContentType
= "text/html";
        Response.Write(
string.Join("\n", _comments.ToArray()));
    }

}

 

  根据IndexJquery,创建View表单IndexJquery.aspx:

<h4>Comments</h4>    
    
<ul id="comments">        
    
</ul>
    
    
<% using (Html.BeginForm("AddComment","Comment",FormMethod.Post,new {@class="hijax"})) { %>    
        
<%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
        
<button type="submit">Add Comment</button>
            
<span id="indicator" style="display:none"><img src="http://www.cnblogs.com/content/load.gif" alt="loading..." /></span>                                
    
<% } %>

 

  在View中引用Jquery:

<script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

 

  添加下面脚本:

<script type="text/javascript">
        
//execute when the DOM has been loaded
        $(document).ready(
function () {
            
//wire up to the form submit event
            $(
"form.hijax").submit(function (event) {
                event.preventDefault();  
//prevent the actual form post
                hijack(this, update_sessions,
"html");
            });
        });

        
function hijack(form, callback, format) {
            $(
"#indicator").show();
            $.ajax({
                url: form.action,
                type: form.method,
                dataType: format,
                data: $(form).serialize(),
                completed: $(
"#indicator").hide(),
                success: callback
            });
        }

        
function update_sessions(result) {
            
//clear the form
            $(
"form.hijax")[0].reset();
            $(
"#comments").append(result);
        }
    
    
</script>

 

  效果:与方式一效果一样

0
相关文章