Skip to content

Instantly share code, notes, and snippets.

@klquast
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klquast/a00f2a32a01a1f88cbe1 to your computer and use it in GitHub Desktop.
Save klquast/a00f2a32a01a1f88cbe1 to your computer and use it in GitHub Desktop.
@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