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());
}
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());
}
相关文章推荐
- How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project
- csharp:Learn how to post JSON string to generic Handler using jQuery in ASP.Net C
- Spring Form Tags - How to use Text Box, Radio Button, Check Box and Drop Down List in Spring
- csharp:Learn how to post JSON string to generic Handler using jQuery in ASP.Net
- How to use jquery ajax and android request security RESTful WCF
- How to use Bundle&Minifier and bundleconfig.json in ASP.NET Core
- using iscroll.js and iscroll jquery plugin in android webview to scroll div and ajax load data.
- How to use HTML-5 data-* attributes in ASP.NET MVC
- Post Json Data by Ajax, and Parse the Json Data in backend
- [Mootools] Simple tutorial of how to use domReady, DOM operation and Ajax in Mootools
- jquery ajax send json to action and get response from action
- Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)
- An example on how to use jQuery and Ajax.NET Professional together
- How to Use Cocoa Bindings and Core Data in a Mac App
- How to POST a django form with AJAX & jQuery
- How to use GET and POST methods in HTTP from a MIDlet
- How to use Asp.Net Mvc ActionFilterAttribute for form authentication
- how to get all controller attribute action and parameter in asp.net mvc
- csharp:Learn how to post JSON string to generic Handler using jQuery in ASP.Net C#.
- Send and Receive JSON objects to Web Service Methods using jQuery AJAX in ASP.Net