Form

Post form via ajax and pass result to Success js function

The Html.Awe.Form helper will make forms of a certain class defined by .FormClass(string) to be posted via ajax, form submission can also be prevented with a confirm dialog by setting .Confirm(bool). A js function can be set to handle the result from the server using .Success(string). Ajax post can be disabled by using .UseAjax(false); The class formLoad is added to show a loading animation when the post takes a long time, the code that does this is in aweUtils.js (init method).
FormDemo/Index.cshtml

@using (Html.BeginForm("AskName", "FormDemo", FormMethod.Post, new { @class = "ajaxForm formLoad" }))
{
@await Html.PartialAsync("AskName", new AskNameInput())
}
<div id="result" style="color: green; min-height: 30px;"></div>

@(Html.Awe().Form()
.FormClass("ajaxForm")
.Confirm(true)
.ConfirmOptions(o => { o.YesText = "Yes, do it !"; o.Message = "Are you sure ?"; })// change default options
.Success("showResult")// js func to be called after successful post
.FillFormOnContent(true))

<script type="text/javascript">
function showResult(o) {
$('#result').html('server says your name is ' + o.Name);
}
</script>
Demos/Helpers/FormDemoController.cs
public IActionResult AskName(AskNameInput input)
{
if (input.Delay)
{
Task.Delay(2000).Wait();
}

if (!ModelState.IsValid) return PartialView(input);

return Json(new { Name = input.FName + " " + input.LName });
}

Form used to post form via ajax and replace the content of the form with the result

Say something:
FormDemo/Index.cshtml
@using (Html.BeginForm("FillForm", "FormDemo", FormMethod.Post, new { @class = "c2" }))
{
@await Html.PartialAsync("FillForm")
}

@(Html.Awe().Form()
.FormClass("c2")
.FillFormOnContent(true) /* when true and the result is Content/View, the result will be used to fill the form's content*/
.BeforeSubmit("validate"))

<script type="text/javascript">
function validate() {
if (!$('#SaySomething').val()) {
alert('please write something in the textbox');
return false;
}
return true;
}
</script>

Used to confirm a form post, and post the form without ajax

FormDemo/Index.cshtml
@using (Html.BeginForm("Index", "FormDemo", FormMethod.Post, new { @class = "normalPost" }))
{
@Html.AntiForgeryToken()
<input type="text" name="word" value="click the button" />
<input type="submit" value="Submit" class="awe-btn mbtn" />
}
@(Html.Awe().Form()
.UseAjax(false)
.Confirm(true)
.FormClass("normalPost")
.Tag(new { target = "confirmCont" }))
<div id="confirmCont"></div>
@*used for the inline popup*@



Comments