JavaScript Failing in Partial View MVC - javascript

I had a MVC 5 view which has a tab control. I have the following view
#using System.Collections
#using MyComp.Content.Text;
#using MyComp.Utilities;
#using System.Linq;
#model MyComp.Models.ViewModels.AdministratorViewModel
<style type="text/css">
...
</style>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-2.0.0.js"></script>
<div class="manage">
<ul class="nav nav-tabs" id="myTab">
<li class="active">
<a data-toggle="tab" href="#invite">
<span class="glyphicon glyphicon-inbox"></span>Invite
</a>
</li>
<li>
<a data-toggle="tab" href="#custom_invite">
<span class="glyphicon glyphicon-pencil"></span>Custom Invite
</a>
</li>
</ul>
<div class="tab-content">
<div id="invite" class="tab-pane active fade in">
#Html.Partial("_InvitePartial", Model)
</div>
<div id="custom_invite" class="htmlCode tab-pane fade">
#Html.Partial("_CustomInvitePartial", Model)
</div>
</div>
</div>
#section scripts {
<script>
function onSuccess(result) {
$('#notify_failure_message').html(result.notify_failure);
$('#notify_success_message').html(result.notify_success);
}
</script>
<script>
$(function () {
$("input[type=button]").click(function () {
var data_email = $('#email').val();
var data_product = $('#product option:selected').text();
$.ajax({
url: 'Tools/SendInvite',
type: 'POST',
data: { email: data_email, product: data_product },
success: function (result) {
$('#fail_message').html(result.result_failure);
$('#success_message').html(result.result_success);
}
});
});
});
</script>
}
and my partial view as
#using System.Collections
#using MyComp.Content.Text;
#using MyComp.Utilities;
#using System.Linq;
#model MyComp.Models.ViewModels.AdministratorViewModel
#using (Html.BeginForm("SendInvite", "Tools", FormMethod.Post,
new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h2>Invite Users</h2>
<div class="form-group">
#Html.LabelFor(m => m.EmailAddress, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EmailAddress,
new { #class = "form-control", id = "email" })
#Html.ValidationMessageFor(m => m.EmailAddress)
</div>
</div>
<div class="form-group">
#Html.Label("Access To", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Product", new SelectList(
new List<Object> {
new { Text = "ProcuctA", Value = "ProcuctA" },
new { Text = "ProcuctB", Value = "ProcuctB" },
new { Text = "All", Value = "All" }},
"Value",
"Text"),
new { #class = "form-control", id = "product" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<span id="fail_message" class="label label-danger"></span>
<span id="success_message" class="label label-success"></span>
#*<p class="text-info">Test Message</p>*#
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="invite_button" value="Invite User" class="btn btn-primary" />
</div>
</div>
}
Bu my button id="invite_button" won't fire the controller method. When I had everything in a single view it did fire and all was fine, this was using the same java script, why has this stopped working when I have moved to a partial view?
Thanks for your time.
Edit. my main view that hosts the partial views is
#using System.Collections
#using VisasysNET.Content.Text;
#using VisasysNET.Utilities;
#using System.Linq;
#model VisasysNET.Models.ViewModels.AdministratorViewModel
<style type="text/css">
span {
padding-right: 10px;
}
...
</style>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-2.0.0.js"></script>
<div class="manage">
<ul class="nav nav-tabs" id="myTab">
<li class="active">
<a data-toggle="tab" href="#invite">
<span class="glyphicon glyphicon-inbox"></span>Invite
</a>
</li>
<li>
<a data-toggle="tab" href="#custom_invite">
<span class="glyphicon glyphicon-pencil"></span>Custom Invite
</a>
</li>
</ul>
<div class="tab-content">
<div id="invite" class="tab-pane active fade in">
#Html.Partial("_InvitePartial", Model)
</div>
<div id="custom_invite" class="htmlCode tab-pane fade">
#Html.Partial("_CustomInvitePartial", Model)
</div>
</div>
</div>
#section scripts {
<script>
function onSuccess(result) {
$('#notify_failure_message').html(result.notify_failure);
$('#notify_success_message').html(result.notify_success);
}
</script>
<script>
$(function () {
$("input[type=button]").click(function () {
var data_email = $('#email').val();
var data_product = $('#product option:selected').text();
$.ajax({
url: 'Tools/SendInvite',
type: 'POST',
data: { email: data_email, product: data_product },
success: function (result) {
$('#fail_message').html(result.result_failure);
$('#success_message').html(result.result_success);
}
});
});
});
</script>
}

section's do not work within partial views,
see here:
Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

invite_button does not have any javascript referencing it. Neither is it of type submit. This button will always do nothing.
It looks like you expect it to be of type submit.
<input type="submit" id="invite_button" value="Invite User" class="btn btn-primary" />

Try modifying the input button type from submit to button - it will work.. I tried with alert in a sample application and it worked.. for me. Below is the code.
Here's the MVC index view
<script type="text/javascript">
$(document).ready(function () {
$("input[type=button]").click(function () {
alert("hello from partial class");
});
});
</script>
<h2>#ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
</p>
<div>
#Html.Partial("~/Views/Home/_MyTest.cshtml")
and here the partial view
#{
ViewBag.Title = "_MyTest";
}
<div>
<input type="button" id="invite_button" value="Invite User"/>
</div>
So on click on the button I am able to the jquery and alert popup's up
hope this helps..

you need to render scripts in your layout view.
<body>
<!-- Other Code -->
#RenderSection("scripts", required: false)
</body>

Related

MVC5. How to hold dialog form size when validation error has appeared

Issue : When user edit item from the list(in dialog form) and entered more than allowed symbols the dialog form changed it's size.(After validation error occurred (See screen attached)
How it opens in edit mode
After Validation error occurred, form size changed
View:
#model Maintenance.Models.AppVersion
#using (Html.BeginForm())
{
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit App Version</h4>
</div>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.AppVersion1)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group margin-bottom">
#Html.LabelFor(model => model.AppVersionDescription, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AppVersionDescription, new { htmlAttributes = new { #class = "form-control", autofocus = "" } })
#Html.ValidationMessageFor(model => model.AppVersionDescription, null, new { #class = "field-validation-error-tooltip" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save changes" id="approve-btn" />
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Moving Pro Services</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
#if (HttpContext.Current.User.Identity.IsAuthenticated)
{
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Moving Pro Services", "Index", "Home", new {area = ""}, new {#class = "navbar-brand"})
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
Services <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>#Html.ActionLink("Companies", "Index", "Companies")</li>
<li>#Html.ActionLink("App Versions", "Index", "AppVersions")</li>
#if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Administrator"))
{
<li>#Html.ActionLink("Create User", "Register", "Account")</li>
}
}
</ul>
</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
}
</div>
<div class="container body-content">
#RenderBody()
<hr/>
<footer>
<p>© #DateTime.Now.Year - Moving Pro Services</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
</body>
</html>
Script(Show dialog):
$(function () {
$.ajaxSetup({ cache: false });
$(document).on("click", ".modal-link", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(document).on("click", "a[data-modal]", function (e)
{
$('#myModalContent').load(this.href, function ()
{
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(window.document).on('shown.bs.modal', '.modal', function () {
window.setTimeout(function () {
$('[autofocus]', this).focus();
}.bind(this), 100);
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
var isValid = true; // assume all OK
$('form').validate(); // perform validation on the form
$('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..
if (!$(this).valid()) {
isValid = false; // signal errors
return false; // break out of loop
}
});
if (!isValid) {
return false; // exit
}
$('#progress').show();
$.ajax({
url: this.action,
modal: true,
draggable: true,
resizable: false,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myModal').modal('hide');
$('#progress').hide();
//location.reload();
alert(result.message);
}
});
return false;
});
}
Index:
#model Maintenance.Models.AppVersionsSearchModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>App Versions</h3>
#using (Html.BeginForm("index", "AppVersions", FormMethod.Get))
{
<div class="row">
<div class="form-horizontal">
<div class="col-lg-3">
#Html.TextBoxFor(m => m.AppVersion1, new { #class = "form-control", #placeholder = "App Version" })
</div>
<div class="col-lg-3" style="vertical-align: bottom;">
<input name="SearchButton" type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
</div>
<div class="grid-control grid-control-app-version">
#{
var grid = new WebGrid(canPage: true,
rowsPerPage: Model.PageSize,
canSort: true,
ajaxUpdateContainerId: "grid"
);
grid.Bind(Model.AppVersions, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(
fillEmptyRows: false,
tableStyle: "webgrid-table webgrid-table-app-version",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column(header: "Action", canSort: false, style: "action",
format: #<text>
#Html.Raw("<a data-modal='' href='/AppVersions/Details/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Detail'> <span class='glyphicon glyphicon-list-alt'> </span> </a>")
#Html.Raw("<a data-modal='' href='/AppVersions/Edit/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Edit'> <span class='glyphicon glyphicon-edit'> </span> </a>")
#Html.Raw("<a data-modal='' href='/AppVersions/Delete/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Delete'> <span class='glyphicon glyphicon-trash'> </span> </a>")
</text>
),
grid.Column(columnName: "AppVersion1", header: Sorter("AppVersion1", "App Version", grid), style: "AppVersion-AppVersion1"),
grid.Column(columnName: "AppVersionDescription", header: Sorter("AppVersionDescription", "App Version Description", grid), style: "AppVersion-AppVersionDescription"),
grid.Column(columnName: "CreateDate", header: Sorter("CreateDate", "Creation Date", grid), style: "AppVersion-CreateDate")
)
)
;
}
</div>
}
<div class="row">
<div class="form-horizontal">
<div class="col-lg-3">
#Html.ActionLink("Create New App Version", "Create", null, htmlAttributes: new { #class = "modal-link btn btn-primary", data_target = "#myModal", data_toggle = "myModal" })
</div>
</div>
</div>
#functions {
public static string Sorter(string columnName, string columnHeader, WebGrid grid)
{
return string.Format("{0} {1}", columnHeader, grid.SortColumn == columnName ?
grid.SortDirection == SortDirection.Ascending ? "▲" :
"▼" : string.Empty);
}
}
#section scripts{
#Scripts.Render("~/scripts/ProcessingModalDialog.js")
}
<script type="text/javascript">
$(function () {
$('th a, tfoot a').click(function () {
$('form').attr('action', $(this).attr('href')).submit();
return false;
});
});
</script>
If you look at the lines in your modal.
<div class="col-md-8">
#Html.EditorFor(model => model.AppVersionDescription, new { htmlAttributes = new { #class = "form-control", autofocus = "" } })
#Html.ValidationMessageFor(model => model.AppVersionDescription, null, new { #class = "field-validation-error-tooltip" })
</div>
When you run your code right click on the modal entry box and check the html generated. You will see that the EditorFor template and ValidationMessageFor become one line as the Validation is added into the as a .
You have a choice, you can style the Modal width and set a max-width class to your EditorFor entry to the wraps to the line underneath.
Or
You can put the ValidationMessageFor outside the Current block and try that.

ASP.NET MVC Multiple registration forms submitting issue

I have multiplebutton in one view for now.
For example, Admin and Student.
If I click the Adminbutton, the view will show a popup modal-dialog of the Admin registration form and the same goes to Student.
The following is the code that I written in cshtml:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="container">
-- the button | admin --
Admin Modal
<div class="modal fade" id="AdminModal" style="width:auto">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title" >Admin Modal</h3>
</div>
<div class="modal-body">
<form id="AdminForm">
-- with other textfields ---
-- and DropDownList for selecting User role, eg. Admin/Student --
</form>
</div>
<div class="modal-footer">
Cancel
<input type="reset" value="Submit" class="btn btn-success" id="btnSubmit" />
</div>
</div>
</div>
</div>
</div>
<div class="container">
-- the button | student --
Student Modal
<div class="modal fade" id="StudentModal" style="width:auto">
<div class="modal-dialog">--student form content--<div>
</div>
</div>
}
Provided with .Js:
$(document).ready(function () {
$("#btnSubmit").click(function () {
var AdminFormdata = $("#AdminForm").serialize();
$.ajax({
type: "POST",
url: "/Account/Register",
data: AdminFormdata,
success: function (d) {
console.log(d);
$("#AdminModal").modal("hide");
}
})
})
});
I tried with the Admin dialog, the above code does work to popup the particular dialog. However when I click the Submit button, it does not get the appropriate data from the chosen registration form. What is the problem here?
HTML does not allow to nest a <form> inside another <form>. Move the <div class="modal "> outside of the #using(Html.BeginForm) block.
Something like this:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
Admin Modal
} #* close main form here! *#
<div class="modal fade" id="AdminModal" style="width:auto">
#* ... *#
<form id="AdminForm"> ... </form>
</div>

jQuery textbox change event doesn't fire, mvc

I am trying to fire a method in JQuery, but it won't work.
#using (Html.BeginForm("AddOrUpdateMethod", "Controller", FormMethod.Post))
{
//some code
<div class="row">
<div class="period-list">
<span class="advance-season">
<span class="glyphicon glyphicon-warning-sign margin-right10"></span>Something
</span>
#for (int i = 0; i < Model.Periods.Count; i++)
{
<div class="form-group period">
#Html.HiddenFor(model => model.Periods[i].Id, new { #Value = Model.Periods[i].Id })
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].From, "{0:dd/MM/yyyy}", new { #class = "form-control period-from", #onchange = "periodChange();" })
<span class="icon"></span>
</div>
</div>
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].To, "{0:dd/MM/yyyy}", new { #class = "form-control period-to" })
<span class="icon"></span>
</div>
</div>
}
//some code
</div>
</div>
}
And my jQuery:
<script type="text/javascript">
function periodChanged() {
$('.period-from .period-to').change(function () {
alert("click");
//some code
});
}
As you can see I tried already adding #change to textBox control. Nothing is happening. Maybe I should mention as well, that i I am using validation on model.Periods.From and model.Periods.To. Moreover this view is a partial view.
EDIT:
I changed into:
<script type="text/javascript">
$(document).ready( function () {
$('.period-from .period-to').click(function () {
alert("click");
if (Model.Periods.All(p=>p.To.Day - p.From.Day + 1 <= 7)) {
}
});
});
but it still doesn't work.
Try this way
$(document).on('change','.period-from .period-to') {
alert("click");
//some code
});
#using (Html.BeginForm("AddOrUpdateMethod", "Controller", FormMethod.Post))
{
//some code
<div class="row">
<div class="period-list">
<span class="advance-season">
<span class="glyphicon glyphicon-warning-sign margin-right10"></span>Something
</span>
#for (int i = 0; i < Model.Periods.Count; i++)
{
<div class="form-group period">
#Html.HiddenFor(model => model.Periods[i].Id, new { #Value = Model.Periods[i].Id })
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].From, "{0:dd/MM/yyyy}", new { #class = "form-control period-from", #onchange = "periodChange();" })
<span class="icon"></span>
</div>
</div>
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].To, "{0:dd/MM/yyyy}", new { #class = "form-control period-to" })
<span class="icon"></span>
</div>
</div>
}
//some code
</div>
</div>
}
#*call the jquery.js file in the main or here*#
<script type="text/javascript">
$(document.ready(function(){
$('.period-from .period-to').change(function () {
alert("click");
//some code
});
});
</script>
this will fire the alert , but this is not enough for your case, you have to do more than this, as the list is generated in loop
your partial view should look like this, attaching the event after the C# code

Page keeps loading when inserting reference to jquery

I really feel this is a stupid question but I could not figure out:
Here my cshtml file, and it's rendered just fine:
#model CrashTestScheduler.Entity.Model.Channel
#{
string editFormat = string.Format("<button type='button' class='editForm' data-val-id=\"{0}\"><span class='ico-edit'></span></button>", ".Id");
const string DeleteFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('deleteChannel', { params:{ id: .Id } })\"><span class='ico-del'></span></button>";
const string EditFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('editChannel', { params:{ id: .Id } })\"><span class='ico-edit'></span></button>";
}
<script>
$(function() {
awe.popup = bootstrapPopup;
});
var getChannelGroupNameHandler = function (item) {
if (item.ChannelGroupName == null || item.ChannelGroupName=='') {
item.ChannelGroupName = $("#ChannelGroupId option:selected").text();
}
}
</script>
<div id="wrap">
<div id="page-heading">
<ol class="breadcrumb">
<li>Home</li>
<li class="active">Channels</li>
<li style="display:none;"></li>
</ol>
</div>
<div class="container">
<div class="col-md-12" id="gridRowChannels">
<div class="col-md-12">
<div class="panel panel-midnightblue-header">
<div class="panel-heading">
<h3>Channel List</h3>
<div class="options">
</div>
</div>
<div class="panel-body">
<div class="row-sub">
<button type="button" id="btnAddProject" class="btn btn-primary" onclick="awe.open('createChannel')">
Add Channel
</button>
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("createChannel").Url(Url.Action("Create", "ChannelsGrid")).Success("itemCreated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Add").Title("Add Channel")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("deleteChannel").Url(Url.Action("Delete", "ChannelsGrid")).Success("itemDeleted('ChannelsGrid')").Parameter("gridId", "ChannelsGrid").Height(200).Modal(true).Title("Delete Channel").OkText("Delete")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("editChannel").Group("Channel").Url(Url.Action("Edit", "ChannelsGrid")).Success("itemUpdated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Save").Title("Edit Channel")
</div>
<div class="row-sub">
#(Html.Awe().Grid("ChannelsGrid")
.Url(Url.Action("GetItems", "ChannelsGrid"))
.Columns(
new Column {Name = "Name", Header = "Channel Name", Sort = Sort.Asc},
new Column {Name = "ChannelGroup.Name", Header = "Channel Group", ClientFormat = ".ChannelGroupName"},
new Column {ClientFormat = DeleteFormat, Width = 50},
new Column {ClientFormat = EditFormat, Width = 50}
)
.Sortable(true)
.SingleColumnSort(true)
.LoadOnParentChange(false)
.PageSize(20)
.Groupable(false))
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12" id="pnlEditproject" style="display: none;">
</div>
</div>
</div>
But I want to use jquery to use jquery validation later on. So here I inserted them to the file.
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
Now the file could not be rendered and the page keeps loading and loading. Any clues?
Looks like you already have access to jQuery library in this page since you are using...
$(function() {
awe.popup = bootstrapPopup;
});
Please remove the new references and try to view page source to find out the list of libraries that are already available.

How do I show a loading spinner when submitting for a partial view in asp.net MVC?

I've written an application that loads partial views when you click "Continue". Sometimes the server hangs a little so I'd like to show some sort of loading message or spinner when the user clicks submit so they know the page is doing something.
This is just your standard form but my submit code looks like this(included a field so you can see an example):
<div class="form-group">
#Html.LabelFor(m => m.JointAdditionalIncomeSource, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
<div class="col-sm-4">
#Html.TextBoxFor(m => m.JointAdditionalIncomeSource, new { #class = "form-control", placeholder = "Additional Income Source" })
#Html.ValidationMessageFor(m => m.JointAdditionalIncomeSource)
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-3 col-sm-10">
<div class="col-sm-4">
<input type="submit" value="Back" id="back" class="btn btn-default" />
<input type="submit" value="Continue" id="continue" class="btn btn-default" />
</div>
</div>
</div>
I've looked around on google for ways to do this and so far haven't had any luck. Jquery wouldn't be a bad method to use if anyone has an example of that.
Updates:
This is my current code that is not working.
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
$('#continue').submit(function () {
$('#LoanType').hide();
});
</script>
<script type="text/javascript">
function onBegin() {
$("#divLoading").html('<image src="../Content/ajax-loader.gif" alt="Loading, please wait" />');
}
function onComplete() {
$("#divLoading").html("");
}
</script>
<body>
<!--If user has javascript disabled-->
<noscript>
<div style="position: fixed; top: 0px; left: 0px; z-index: 3000;
height: 100%; width: 100%; background-color: #FFFFFF">
<p style="margin-left: 10px">To continue using this application please enable Javascript in your browser.</p>
</div>
</noscript>
<!-- WIZARD -->
<div id="MyWizard" class="site-padding-top container">
<div data-target="#step1" id="step1" class="app-bg">
<div class="form-horizontal">
<div id="LoanType">
<div class="divider-app">
<p>Loan Type</p>
</div>
#using (Ajax.BeginForm("SelectLoanType", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "step2" }))
{
<div class="form-group">
#Html.LabelFor(m => m.LoanType, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
<div class="col-sm-4">
#Html.DropDownListFor(m => m.LoanType, new SelectList(Model.AllAvailableLoanTypes.Select(x => new { Value = x, Text = x }), "Value", "Text"), new { #class = "form-control", id = "loanType" })
</div>
</div>
</div>
<div class="form-group" id="LoanTypeSubmit">
<div class="col-lg-offset-3 col-sm-10">
<div class="col-sm-4">
<input type="submit" value="Continue" id="continue" class="btn btn-default" />
</div>
</div>
</div>
}
<div id="divLoading"></div>
</div>
The delay in the controller is working.
Here goes the complete solution -
Lets say you have an ajax controller like this -
public ActionResult Ajax()
{
return View();
}
Which serves the following ajax view -
#{
ViewBag.Title = "Ajax";
}
<h2>Ajax</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function onBegin() {
$("#divLoading").html('<image src="../Content/ajax-loader.gif" alt="Loading, please wait" />');
}
function onComplete() {
$("#divLoading").html("");
}
</script>
#using (Ajax.BeginForm("LoadRules", "Home", new AjaxOptions { UpdateTargetId = "Rules", OnBegin = "onBegin", OnComplete = "onComplete" }))
{
<input type="submit" value="Load Rules" />
}
<div id="divLoading"></div>
<div id="Rules"></div>
Then when you click on the submit button it will hit the following controller, which has a delay of 5 secs (simulation of long running task) in serving the partial view -
public ActionResult LoadRules(DDLModel model)
{
System.Threading.Thread.Sleep(5000);
return PartialView("MyPartial");
}
and the partial view is a simple view -
<div>
This is Partial View
</div>
Here to show the loaded I simply used the following gif file -
when we click on the submit button it will show the progress in the following way -
And once the delay of 5 secs completes on the server side, it will show the partial view -
The answer by ramiramilu is fairly close, but our Team was unable to integrate Ajax into our MVC 5 web app. There were other issues as well. So I am going to (more or less) duplicate his answer with some minor bug fixes.
Here goes the complete solution -
Lets say you have an ajax controller like this -
public ActionResult Ajax()
{
return View();
}
Which serves the following ajax view -
#{
ViewBag.Title = "Ajax";
}
<h2>Ajax</h2>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js" integrity="sha512-YHQNqPhxuCY2ddskIbDlZfwY6Vx3L3w9WRbyJCY81xpqLmrM6rL2+LocBgeVHwGY9SXYfQWJ+lcEWx1fKS2s8A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function onBegin() {
$("#divLoading").html('<image src="../Content/ajax-loader.gif" alt="Loading, please wait" />');
}
function onComplete() {
$("#divLoading").html("");
}
</script>
<form asp-action="LoadRules" asp-controller="Home" method="POST" data-ajax="true" data-ajax-update="#Rules" data-ajax-begin="onBegin" data-ajax-complete="onComplete">
<input type="submit" value="Load Rules" />
</form>
<div id="divLoading"></div>
<div id="Rules"></div>
Then when you click on the submit button it will hit the following controller, which has a delay of 5 secs (simulation of long running task) in serving the partial view -
public PartialViewResult LoadRules(DDLModel model)
{
System.Threading.Thread.Sleep(5000);
return PartialView("MyPartial", model);
}
and the partial view is a simple view -
<div>
This is Partial View
</div>
Here to show the loaded I simply used the following gif file -
when we click on the submit button it will show the progress in the following way -
And once the delay of 5 secs completes on the server side, it will show the partial view -

Categories