Zapnologica Zapnologica - 1 year ago 76
jQuery Question

Ajax.BeginForm loading result in page

I am trying to do an AJax form post, and when it is succesfull update a table with the results.

here is my code:

@using (Ajax.BeginForm("AddTagToSubject", "Subjects", null, new AjaxOptions() { OnSuccess = "UpdateTableData();" }, null))
<div class="form-">
<div class="form-horizontal">
@Html.Hidden("SubjectId", Model.Id)
<div class="form-group">
@Html.Label("Add Tag", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-4">
@Html.TextBox("Tag", "", new { @class = "form-control" })
<div class="col-md-2">
<input type="submit" value="Add" class="btn btn-default" />

here is my script at bottom of page:

<script type="text/javascript">
//Get the latest tags
function UpdateTableData() {
console.log("Called fucntion");

Here is my action method:

public async Task<JsonResult> AddTagToSubject(AddTagToSubjectViewModel model)
model.Tag = model.Tag.ToLowerInvariant();
var tags = await db.Tags.FirstOrDefaultAsync(x => x.Name == model.Tag);
if (tags == null)
tags = new Tag { CreatedBy = User.Identity.GetUserId(), DateCreated = DateTime.UtcNow, Name = model.Tag };
await db.SaveChangesAsync();
var subject = await db.Subjects.FirstOrDefaultAsync(x => x.Id == model.SubjectId);
await db.SaveChangesAsync();
return Json(subject.Tags.Select(x => new { Id = x.Id, Name = x.Name }).ToList(), JsonRequestBehavior.AllowGet);

Now when I add a tag, it calls the action method everything works. It adds the tag to the db. But on my front end, Instead of calling my
OnSuccess' function. It just reloads the whole webpage and displays my
JSON` result.

[{"Id":3,"Name":"Zulu"},{"Id":7,"Name":"accounting"},{"Id":6,"Name":"High School"}]

I have the following included in my layout file:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

What am I missing here?

Answer Source

You have to include jquery.unobtrusive-ajax.js and maybe you have change your Ajax.BeginForm's OnSuccess function like this:

@using (Ajax.BeginForm("AddTagToSubject", "Subjects", null, 
         new AjaxOptions() { OnSuccess = "UpdateTableData" }, null)){...}