Create a gist now

Instantly share code, notes, and snippets.

@klquast /AjaxTestController Secret
Last active Aug 29, 2015

What would you like to do?
@using WebApplication1.Models
@model AjaxTestIndexModel
<div class="row">
<div class="form-group">
<label class="col-sm-2 control-label">
@Html.DisplayNameFor(m => m.Name)
</label>
<div class="col-sm-6">
@Html.TextBoxFor(m => m.Name)
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
@Html.DisplayNameFor(m => m.Subject)
</label>
<div class="col-sm-6">
@Html.TextBoxFor(m => m.Subject)
</div>
</div>
</div>
<div class="alert alert-danger">
@Html.ValidationSummary()
</div>
<div class="buttons">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
public class AjaxTestController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult PostTest(AjaxTestIndexModel model)
{
if (model == null)
{
throw new ArgumentNullException("model");
}
if (!ModelState.IsValid)
{
return PartialView("_TheForm", model);
}
return new JsonResult
{
Data = new { Success = true }
};
}
}
public class AjaxTestFormModel
{
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Subject")]
public string Subject { get; set; }
}
@{
ViewBag.Title = "Ajax Test";
var options = new AjaxOptions()
{
Url = Url.Action("PostTest", "AjaxTest"),
HttpMethod = "POST",
UpdateTargetId = "update-target",
OnSuccess = "alert('success');",
OnFailure = "alert('fail');"
};
}
<style type="text/css">
.form-group {
clear: both;
overflow: hidden;
}
</style>
<h2>@ViewBag.Title</h2>
<div class="update-target" id="update-target">
@using(Ajax.BeginForm(options))
{
@Html.Partial("_TheForm")
}
</div>
...
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval") // Add this line!
...
...
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*", // Add this line!
"~/Scripts/jquery.validate*"));
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment