I have an Action Method that returns a JSON-serialized object. The problem I m having is that the JSON returned is opening in a new page, instead of being processed by the "success" function of the jquery.Ajax method.
Here s the controller action:
[HttpPost]
public ActionResult AddAssignment(AssignmentViewModel avm)
{
db.Assignments.Add(new Assignment
{
Name = avm.Name,
DueDate = DateTime.Parse(avm.DueDate),
CourseID = avm.CourseID,
IsComplete = false
});
db.SaveChanges();
avm.Course = db.Courses
.Where(x => x.CourseID == avm.CourseID)
.SingleOrDefault()
.Name;
return Json(avm);
}
The View (form):
@model Fooburg.Mvc.Models.AssignmentViewModel
<h2 style="margin: 0 0 24px 0">Add Assignment:</h2>
@using (Html.BeginForm("AddAssignment",
"Assignments",
FormMethod.Post,
new { @id = "add-assignment-form" }))
{
<dl class="tabular">
<dt>Course:</dt>
<dd>
@Html.DropDownListFor(x => x.CourseID, new SelectList(ViewBag.Courses, "CourseID", "Name"))
</dd>
<dt>Assignment:</dt>
<dd>
@Html.TextBoxFor(x => x.Name)
</dd>
<dt>Due Date:</dt>
<dd>
@Html.TextBoxFor(x => x.DueDate, new { @class = "date" })
<script type="text/javascript">
$(function () {
$( .date ).datepicker({ dateFormat: "mm/dd/yy" });
});
</script>
</dd>
</dl>
<p>
<input type="submit" value="Add Assignment" id="new-assignment-submit" />
</p>
}
这里还有 j:
$(function () {
$( #add-assignment-form ).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$( #output ).html(result);
}
});
});
});
我尝试了<代码>event.Propogation()方法,但并没有改变我的问题。
EDIT: I ve updated my javascript to the following, but I m still getting the same result
$( #add-assignment-form ).submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$( #output ).html(result);
}
});
return false;
});