您的位置:首页 > Web前端 > JQuery

How to use JSon data in mvc action and post form data use JQuery ajax

2011-09-20 23:21 901 查看
原文连接: http://www.flyear.net/Artical/How-To-Use-JSon-Data-In-MVC-Action-and-post-form-data-use-jquery-ajax

1. Front-End Html:

@using (Html.BeginForm("NewComment", "Home", new { area = "Blog" }, FormMethod.Post, new { id = "commentForm" }))
{
    <hr />
    <input id="articalId" type="hidden" value="@Model.Post.PostID" />
    <ul>
        <li><span>User</span><input id="commenterName" type="text" /></li>
        <li><span>Email</span><input id="commenterEmail" type="text" /></li>
        <li><span>Site</span><input id="commenterSite" type="text" /></li>
        <li><span>Comment Content</span><p>
            <textarea id="commenterContent" cols="35" rows="10"></textarea></p>
        </li>
        <li>
            <input id="commentSubmit" type="submit" value="Submit" /></li>
    </ul>
}
 

2. Front-End JavaScript:

$("#commentForm").submit(function () {
            var odata = GetCurrentComment();
            if (oldSubmitComment != null || oldSubmitComment != undefined) {
                if (odata.Content == oldSubmitComment.Content) {
                    $("#msg").html("<span style=\"color: Red\"><strong>You already submited this comment, please add new content for submit.</strong></span>");
                    return false;
                }
            }
            oldSubmitComment = odata; //Set old submit comment to current submit data
            var json_strng = JSON.stringify(odata);
            var beforeDate = new Date();

            $.ajax({
                url: $("#commentForm").attr("action"),
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: json_strng,
                success: function (result, status) {
                    if (result.Success) {
                        AppenderNewCommentToEnd(odata);
                        var completeDate = new Date();
                        $("#msg").html("Your spend <span style=\"color: Red\"><strong>" + (completeDate - beforeDate) + " Milliseconds </strong></span>on this submit, Thanks for your time.");
                    }
                    else {
                        $("#msg").html("<span style=\"color: Red\"><strong>Your submit fauiler, Detail message is:" + json2.ErrorMessage + "</strong></span>");
                    }
                }
            });
            return false;
        });

 

 

function TrArticalComment(articalId, name, email, site, date, content) {
        this.PostID = articalId;
        this.UserName = name;
        this.Email = email;
        this.WebAddress = site;
        this.Date = date;
        this.Content = content;
    }
    //Page Transfer Model       
    function GetCurrentComment() {
        var comment = new TrArticalComment(
                $("#articalId").val(),
                $("#commenterName").val(),
                $("#commenterEmail").val(),
                $("#commenterSite").val(),
                new Date(),
                $("#commenterContent").val());
        return comment;
    }
    function AppenderNewCommentToEnd(comment) {
        $("<hr/><div class=\"commentHeader\"> <a href='" + comment.WebAddress + "' target=\"_blank\"><span class=\"commentUser\">" + comment.UserName + "</span></a> <span class=\"commonDate\">"
                + comment.Date + "</span></div><div class=\"commonContent\">" + comment.Content + "</div>").appendTo("#newCommentHere");
    }

 

3. Back-End code:

[HttpPost]
        public JsonResult NewComment(NewCommentDto comment)
        {
            var pComment = comment.ToPostComment();
            PostService.AddComment(pComment.PostID, pComment);
            return Json(new { Success = true, Message = "Successfully" });
        }

 

4. Some things need more attentation:

We need add ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); into Application_Start method in Global.axsx.cs to support Action receive JSon format data.

 

protected void Application_Start()
        {
            logger.Info("LightBlog log system started.");

            LightBlog.Infrastructure.RepositoryFramework.NHibernateProvider.DataContext.ReCreateDatabase();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: