validator - unobtrusive form reset not working - javascript

I'm using adminlte v 3.0.1. bootstrap
doing some validator and unobtrusive
stuck at resetting form, in example
edit => show modal form => trigger validation => cancel => new => validation result still there
I'm already tried
$('#form').trigger('reset')
~ not doing anything (not triggering anything)
$('#form')[0].trigger('reset') ~ trigger is not a function
document.getElementById('form').reset() ~ not doing anything (not triggering anything)
any help is appreciated
regards
update:
HTML code
#{
ViewBag.Title = "Master Currency";
}
<div class="card-header">
<h3>Currency</h3>
</div>
<div class="card-body">
<div class="row src-form" style="margin-bottom: 15px;">
<div class="col-12">
#{
Html.RenderPartial("_Search");
}
</div>
</div>
<div class="row" style="margin-bottom: 15px;">
<div class="col-1">
<a href="javascript:void(0)" title="Search" id="btn-toggle-search">
<i class="fa fa-search-plus custom-fa"></i>
</a>
</div>
<div class="col-1">
<a href="javascript:void(0)" title="Refresh" id="btn-refresh">
<i class="fa fa-sync custom-fa"></i>
</a>
</div>
<div class="col-1 offset-9">
<a href="javascript:void(0)" id="btn-new" class="btn btn-primary">
<span>New</span>
</a>
</div>
</div>
<div class="row">
<div class="col-12">
<table id="grid">
<thead>
<tr>
<th>Currency Code</th>
<th>Currency Name</th>
<th>Created By</th>
<th>Created Time</th>
<th>Last Modified By</th>
<th>Last Modified Time</th>
<th></th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div class="modal fade" id="modal-edit">
<div class="curr-edit">
#using (Ajax.BeginForm("Save", "Currency", new { area = "Master" },
new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "curr-edit",
HttpMethod = "POST",
OnSuccess = "successSave",
OnFailure = "failSave"
}, new { #id = "edit-form" }))
{
#Html.AntiForgeryToken()
#Html.Partial("_Edit")
}
</div>
</div>
<div class="modal fade" id="modal-delete">
<div class="curr-del">
#using (Ajax.BeginForm("Delete", "Currency", new { area = "Master" },
new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "curr-del",
HttpMethod = "POST",
OnSuccess = "successDelete",
OnFailure = "failDelete"
}, new { #id = "delete-form" }))
{
#Html.AntiForgeryToken()
#Html.Partial("_Delete")
}
}))
</div>
</div>
The edit form
#model CurrencyModel
#Html.HiddenFor(model => model.CurrencyID, new { #id = "curcy-id" })
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="title-modal"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row" style="margin-bottom: 15px;">
<div class="col-4">
#Html.LabelFor(model => model.CurrencyCode)
</div>
<div class="col-8">
#Html.TextBoxFor(model => model.CurrencyCode, new { #class = "form-control", #id = "curcy-code" })
#Html.ValidationMessageFor(model => model.CurrencyCode, "", new { #class = "validation-message" })
</div>
</div>
<div class="row" style="margin-bottom: 15px;">
<div class="col-4">
#Html.LabelFor(model => model.CurrencyName)
</div>
<div class="col-8">
#Html.TextBoxFor(model => model.CurrencyName, new { #class = "form-control", #id = "curcy-name" })
#Html.ValidationMessageFor(model => model.CurrencyName, "", new { #class = "validation-message" })
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS Code
$('#grid').DataTable({
'scrollX': true,
'scrollY': true,
'serverSide': true,
'fixedColumns': true,
'sScrolling': true,
'ScrollY': '400px',
'ScrollX': '800px',
'bScrollCollapse': true,
'bSortCellsTop': true,
"sDom": 'Rfrtlip',
"dom": '<"top"i>rt<"bottom"lp><"clear">',
'ajax': {
'url': '#Url.Action("GetCurrency", "Currency", new { area = "Master" })',
'type': 'POST',
'dataType': 'JSON'
},
'columns': [
{ 'data': 'CurrencyCode', 'searchable': true, 'autoWidth': true },
{ 'data': 'CurrencyName', 'autoWidth': true },
{ 'data': 'CreatedBy', 'sortable': false, 'autoWidth': true },
{
'data': 'CreatedTime', 'autoWidth': true, 'sortable': false, 'render': function (jsonDate) {
return convertJsonDate(jsonDate);
}
},
{ 'data': 'LastModifiedBy', 'autoWidth': true, 'sortable': false, 'sortable': false },
{
'data': 'LastModifiedTime', 'autoWidth': true, 'sortable': false, 'render': function (jsonDate) {
return convertJsonDate(jsonDate);
}
},
{
'data': 'CurrencyID', 'width': '50px', 'sortable': false , 'className': 'text-center', 'render': function (data) {
return "Edit"
}
},
{
'data': 'CurrencyID', 'width': '50px', 'sortable': false, 'className': 'text-center', 'render': function (data) {
return "Delete"
}
}
]
});
$(document).ready(function () {
$('#btn-src').click(function () {
var srcparam = $('#src-type').children('option:selected').data('id');
if (srcparam === '' || srcparam === undefined || srcparam === null) {
alert('Pilih kategori pencarian terlebih dahulu!');
return;
}
debugger;
var srcvalue = $('#src-value').val();
if (srcvalue === '' || srcvalue === undefined || srcvalue === null){
alert('Parameter pencarian harus diisi!');
return;
}
oTable = $('#grid').DataTable();
switch (srcparam) {
case 'CODE':
oTable.columns(0).search(srcvalue).draw();
break;
case 'NAME':
oTable.columns(1).search(srcvalue).draw();
break;
}
});
$('#grid').on('click', 'a.btn-edit', function (e) {
var param = parseInt($(this).data('id'));
$.post('#Url.Action("PrepareFormData", "Currency", new { area = "Master" })', { id: param })
.done(function (obj) {
switch (obj.Response) {
case 'SUCCESS':
var validator = $('#edit-form').validate();
validator.resetForm();
$('#edit-form').trigger('reset');
$('#curcy-id').val(obj.Currency.CurrencyID).trigger('change');
$('#curcy-code').val(obj.Currency.CurrencyCode).trigger('change');
$('#curcy-name').val(obj.Currency.CurrencyName).trigger('change');
$('#title-modal').text('Edit Currency');
$('#modal-edit').modal('show');
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg);
break;
}
});
});
$('#grid').on('click', 'a.btn-delete', function (e) {
var param = parseInt($(this).data('id'));
$.post('#Url.Action("PrepareFormData", "Currency", new { area = "Master" })', { id: param })
.done(function (obj){
switch (obj.Reponse) {
case 'SUCCESS':
$('#delete-form').trigger('reset');
$('#curcy-id').val(obj.Currency.CurrencyID).trigger('change');
$('#modal-delete').modal('show');
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg);
break;
}
});
});
$('#btn-new').click(function () {
$.post('#Url.Action("PrepareFormData", "Currency", new { area = "Master" })', { id: 0 })
.done(function (obj) {
switch (obj.Response) {
case 'SUCCESS':
$('#edit-form').trigger('reset');
$('#curcy-id').val(obj.Currency.CurrencyID).trigger('change');
$('#title-modal').text('New Currency');
$('#modal-edit').modal('show');
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg);
break;
}
})
});
});

The issue might be there if you are trying to reset the form when the form is not present in DOM.
Try to reset the form on a Modal open event like this. For example idEditModal is the id of your modal.
$('#idEditModal').on('shown.bs.modal', function (e) {
var $alerts = $('#form');
$alerts.validate().resetForm();
$alerts.find('.error').removeClass('error');
})

Related

Getting new full calendar event in bootstrap modal

I am using bootstrap modal to display event details. When the event will be clicked the start, end and title will be displayed in the popup.
The events are created using a boostrap modal form.
Here is the code
$(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
views: {
month: {
titleFormat: 'YYYY, MM, DD'
}
},
validRange: function(nowDate) {
return {
start: nowDate,
end: nowDate.clone().add(1, 'months')
};
},
navLinks: true,
selectable: true,
selectHelper: true,
select: function(start, end) {
startDate = moment(new Date(start)).format("MM-DD-YYYY");
$('#createBookingModal .modal-header .modal-title span').text(startDate);
$('#createBookingModal').modal('show');
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function(start, end, timezone, callback){
$.ajax({
url: '/api/bookings',
dataType: 'json',
data: {
start: start.unix(),
end: end.unix(),
},
success: function(response){
var events = [];
$(response).each(function(){
events.push({
title: $(this).attr('title'),
start: $(this).attr('start_time'),
end: $(this).attr('end_time'),
});
});
callback(events);
}
});
},
eventClick: function(event, jsEvent, view) {
//Todo
//Get event end date here
console.log(event);
startDate = moment(new Date(event.start)).format("MM-DD-YYYY");
endDate = moment(new Date(event.end)).format("MM-DD-YYYY");
$('#modalTitle').text(event.title);
$('#modalBody .start span').text(startDate);
$('#modalBody .end span').text(endDate);
$('#fullCalModal').modal('show');
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
$('#submitButton').on('click', function(e){
e.preventDefault();
doSubmit();
});
function doSubmit(){
//validate end date here
endDate = new Date($('#bookingEndDate').val());
if (! moment(endDate, 'MM/DD/YYYY', true).isValid() ){
alert('Invalid Date');
} else {
eventData = {
title: $('#bookingName').val(),
start: new Date($('#createBookingModal .modal-header .modal-title span').text()),
end: endDate
};
$.ajax({
url: '/api/bookings/create',
data: {
title: eventData.title,
start_time: eventData.start,
end_time: eventData.end
},
success: function(response){
console.log(response);
// if ( response == 0 ){
// alert('Invalid Date');
// return false;
// } else {
// return true;
// }
}
});
$('#createBookingModal form').get(0).reset();
$("#createBookingModal").modal('hide');
$("#calendar").fullCalendar('renderEvent', eventData, true);
$('#calendar').fullCalendar('unselect');
}
}
});
HTML code
<div class="card-body full-calendar">
<div id='calendar'></div>
<!-- Display Create Booking form in modal -->
<div id="createBookingModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add an Booking on: <span class="startDate"></span>></h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
</div>
<div id="modalBody" class="modal-body">
<form>
<div class="form-group">
<label for="bookingName">Booking Title</label>
<input class="form-control" type="text" placeholder="Booking Name" id="bookingName">
</div>
<div class="form-group">
<label for="bookingEndDate">End Date</label>
<div class="input-group date" data-provide="datepicker">
<input type="text" id="bookingEndDate" class="form-control" placeholder="mm/dd/yyyy">
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
</div>
<!--<div class="form-group">
<textarea class="form-control" type="text" rows="4" placeholder="Booking Description" id= "eventDescription"></textarea>
</div>-->
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="submit" class="btn btn-primary" id="submitButton">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Display Booking in modal -->
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 id="modalTitle" class="modal-title"></h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
</div>
<div id="modalBody" class="modal-body">
<p class="start">Start At: <span></span></p>
<p class="end">End At: <span></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<!-- <button class="btn btn-primary"><a id="eventUrl" target="_blank">Event Page</a></button>-->
</div>
</div>
</div>
</div>
I am not getting the end date for the newly created event when trying to display it in modal, you can notice //todo, that is where I want to get end date.May be it need to delegated, but I have no idea how it should be done?
I have added a fiddle here, you can see, the end date is coming "01-01-1970", because eventClick() is not getting the end date.
Update
It happens only when you are giving same start and end date.
I fixed it with just a small workaround, if anyone has a better solution, feel free to post.
eventClick: function(event, jsEvent, view) {
if ( event.end == null ){
event.end = event.start;
}
startDate = moment(new Date(event.start)).format("MM-DD-YYYY");
endDate = moment(new Date(event.end)).format("MM-DD-YYYY");
$('#modalTitle').text(event.title);
$('#modalBody .start span').text(startDate);
$('#modalBody .end span').text(endDate);
$('#fullCalModal').modal('show');
},
*#ADyson has a huge contribution on this solution, I was expecting to post this as an answer after our discussion, he did not post, so I am posting it.
I had a similar issue (about 2 years ago!) Had to use submitHandler: function(){} like below
submitHandler: function (form) {
var dataRow = CreateDataSetup();
$.ajax({
type: 'POST',
url: "/BookingTwo/SaveEvent",
data: dataRow,
success: function () {
$("#myform")[0].reset();
ClearPopupFormValues();
$('#popupEventForm').modal('hide');
},
statusCode: {
201: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Success Event Created.", "success", 4000)
},
500: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Internal Server Error - Logged with System Admins", "danger", 4000)
$('#popupEventForm').modal('hide');
},
400: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Duration Service Returned 0 - Event NOT Created.", "danger", 4000)
$('#popupEventForm').modal('hide');
},
401: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Warning - You do not have permission to delete this.", "danger", 4000)
$('#popupEventForm').modal('hide');
},
403: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Warning - Can't delete approved events.", "danger", 4000)
},
409: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("There is already an event for the user for this date.", "danger", 4000)
}
}
});
}
Also created a DataSetup funtion -
function CreateDataSetup() {
console.log("Attempting to Setup POST Values...")
var intEtad = parseInt($('#ETADType').val());
var intEtadSub = parseInt($('#ETADSubType').val());
var normStart = $('#LeaveStart').val();
var normEnd = $('#LeaveFinish').val();
var ahStart = $('#ADHOCLeaveStart').val();
var ahEnd = $('#ADHOCLeaveFinish').val();
var dataRow = {
'Id': $('#id').val(),
'Subject': $('#title').val(),
'Description': $('#customdescription').val(),
'StartTime': normStart,
'EndTime': normEnd,
'AHStartTime': ahStart,
'AHEndTime': ahEnd,
'SelectRole': $('#SelectRole').val(),
'ETADType': intEtad,
'ETADSubType': intEtadSub,
'StaffID': $('#StaffID').val(),
'EventStatus': $('#EventStatus').val(),
'AllRoles': $('#AllRoles').is(':checked'),
'AllDay': $('#AllDay').is(':checked'),
'AM': $('#AM').is(':checked'),
'PM': $('#PM').is(':checked'),
'ADHOC': $('#ADHOC').is(':checked'),
};
console.log("Setup Complete");
return dataRow;
}

Get tabs to show up along with view and model on error in mvc controller

I have a set of jquery tabs which each contain a datatable. When i post data on a tab, i want to check if its a duplicate. If its a duplicate i want to load the that view back in (AddLocation.cshtml) but its just loading that view, without the tabs.
Before save:
After save (notice tabs missing):
AddEditLocation.cshtml:
#model APro.Model.DTO.DTOAddEditLocation
#{
ViewBag.Title = "Add Location";
}
<h2>#(Model.LocationId == Guid.Empty ? "Add Location" : "Edit Location")</h2>
<div id="AddEditLocation">
#using (Ajax.BeginForm("SaveLocation", "Management",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "AddEditLocation",
},
new { id = "AddEditLocationForm", #class = "form-horizontal" }))
{
<div class="form-group">
<div class="row">
<div class="col-md-4">
#Html.Label("Location Name", new { #class = "control-label required-field" })
#Html.TextBoxFor(m => m.LocationName, new { #class = "form-control", required = "required" })
</div>
<div class="col-md-4">
#Html.Label("Location Category", new { #class = "control-label required-field" })
#Html.DropDownListFor(x => x.LocationCategoryId,
new SelectList(Model.LocationCategoryList, "Id", "Description"), "-- Please select a company --"
, new { #class = "form-control", required = "required" })
</div>
</div>
</div>
#Html.HiddenFor(x => x.LocationId)
<input type="button" id="btnReset" class="btn btn-default mr10 mb10 mt25" value="Cancel" />
<input type="submit" class="btn btn-primary mr10 mb10 mt25" value="Save" id="saveRole" />
}
</div>
#if ((string)ViewBag.ErrorMessage != null)
{
Html.RenderPartial("~/Views//Error/ErrorDuplicate.cshtml", (string)ViewBag.ErrorMessage);
}
<div id="errorModal"></div>
<script>
$("#AddEditLocation").on('click', '#btnReset', function (event) {
$.get("GlobalData/Index?activeTab=5", function (data) {
$(".body-content").replaceWith(data);
});
});
</script>
ErrorDuplicate.cshtml:
#{
Layout = null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript">
$(function () {
$('.modal').modal('show');
});
</script>
<div class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Error</h4>
</div>
<div class="modal-body">
#Model
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Controller:
public ActionResult Index(int activeTab = 0)
{
ViewBag.ActiveTab = activeTab;
return View("GlobalDataTabs");
}
[HttpPost]
public ActionResult SaveLocation(DTOAddEditLocation obj)
{
var result = _globalDataService.SaveLocation(obj);
if (!result)
{
obj.LocationCategoryList = _globalDataService.GetCategoryLocationList();
ViewBag.ErrorMessage =
"The Location name " + obj.LocationName + " already exists.";
return View("AddEditLocation", obj);
}
return RedirectToAction("Index", new { activeTab = 5 });
}
public PartialViewResult ShowError(String sErrorMessage)
{
return PartialView("~/Views/Error/ErrorDuplicate.cshtml");
}
GlobalDataTabs.cshtml
#{
ViewBag.Title = "Global Data";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Global Data</h2>
<script>
$(document).ready(function () {
$("#GlobalDataTabs").tabs();
var activeTab = '#ViewBag.ActiveTab'
$("#GlobalDataTabs").tabs("option", "active", activeTab);
window.history.replaceState(null, null, window.location.pathname);
});
</script>
<div id="GlobalDataTabs">
<ul>
<li>Category</li>
<li>Subcategory</li>
<li>Subcategory Description</li>
<li>Description Lookup</li>
<li>Location Category</li>
<li>Location</li>
</ul>
<div id="categoryTab">
#Html.Partial("Category")
</div>
<div id="subCategoryTab">
#Html.Partial("Subcategory")
</div>
<div id="subCategoryDescTab">
#Html.Partial("SubcategoryDescription")
</div>
<div id="descLookupTab">
#Html.Partial("DescriptionLookup")
</div>
<div id="locationCategoryTab">
#Html.Partial("LocationCategory")
</div>
<div id="locationTab">
#Html.Partial("Location")
</div>
</div>

How to use Edit in bootsrap Modal asp.net mvc

I'm using asp.net mvc i want to update data in database using a bootsrap modal
And partial Views.
The broblem is when i click on the link to show the Model it's not working (it shows an empty modal)
this is my Code:
//the Controller Action
public ActionResult Edit(int id = 0)
{
Tache tache = db.Taches.Find(id);
if (tache == null)
{
return HttpNotFound();
}
return PartialView("PartialEdit", tache);
}
// the index View that contain the link and the modal definition :
<td>
<a data-modal='' href='"/Tache/edit/"+#item.TacheId' data-id="#item.TacheId" id="#item.TacheId " title=" edit">Edit </a> |
#Html.ActionLink("Delete", "Delete", new { id = item.TacheId })
</td>
<div id='myModal' class='modal fade'>
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
// and this is the Partial View
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Nouvelle Tâche</h4>
</div>
#using (Html.BeginForm("Create", "Tache", FormMethod.Post, new { #id = "formId" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.TacheId)
<div class="modal-body">
//Some forms in inputs
<div class="row">
// Finaly my javascript :
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
location.reload();
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
I think the problem may came from the link that somthing is missing their !!
but i'm not sure
if someone can help me that will be great
Think you
As I have said in my comment the code works perfectly now.
In my Index view I have replaced this:
<a data-modal='' href='"/Tache/edit/"+#item.TacheId' data-id="#item.TacheId" id="#item.TacheId " title=" edit">Edit </a>
To this:
<a data-modal='' href="#Url.Action("Edit", "Tache", new { id = item.TacheId })" data-id="#item.TacheId" id="#item.TacheId " title=" edit">Modifier </a>

Infinity Ajax Request When Drop Change in Knockout MVC

I am using Knockout MVC in my project. I try to pass the viewModel to when Drop Down changing . but when I try this method call several times and the alert "ok" invoke continuesley. Can any one please help me on this??
$(function () {
$('#rmch').change(function () {
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
alert("Ok");
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
});
My Json Method
public JsonResult DropChange(HotelModel hotelmod)
{
//hmodel.RoomModel = new List<RoomModel>();
//for (int i = 1; i <= hmodel.NoOfRooms; i++)
//{
// hmodel.RoomModel.Add(new RoomModel { adultsDrp = ListItems.GetList(1, 6), childDrop = ListItems.GetList(0, 5) });
// //hmodel.RoomModel.Add(new RoomModel { });
//}
var jjj = JsonConvert.SerializeObject(hotelmod);
return Json(hotelmod);
}
My View
<div class="search-tab-content">
<div class="tab-pane fade active in" id="hotels-tab">
<form id="searchfrm">
<div class="title-container">
<h2 class="search-title">Search and Book Hotels</h2>
<p>We're bringing you a new level of comfort.</p>
<i class="soap-icon-hotel"></i>
</div>
<div class="search-content">
<h5 class="title">Where</h5>
<label>Your Destination</label>
#ko.Html.TextBox(m => m.Destination, new { #class = "input-text full-width", #placeholder = "Any destination, country, city code" })
#ko.Html.Hidden(new { #Id = "DesCode" }).Value(m => m.DesCode)
<hr>
<h5 class="title">When</h5>
<div class="row">
<div class="col-xs-4">
<label>Check In</label>
<div class="datepicker-wrap">
#ko.Html.TextBox(m => m.CheckInDate, new { #class = "input-text full-width" })
</div>
</div>
<div class="col-xs-4">
<label>Check Out</label>
<div class="datepicker-wrap">
#ko.Html.TextBox(m => m.CheckOutDate, new { #class = "input-text full-width" })
</div>
</div>
<div class="col-xs-4">
<label>ROOMS</label>
<div class="selector">
#ko.Html.DropDownList(m => m.RoomList, new { #class = "full-width jkl", #id = "rmch" }, "Text", "Value").Value(m => m.NoOfRooms)
</div>
</div>
</div>
<hr>
<div id="p_scentsFH">
#using (var rmModel = ko.Foreach(m => m.RoomModel))
{
<h5 class="title">Room 1</h5><div class="row">
<div class="col-xs-3">
<label>ADULTS</label>
<div class="selectorgen">
#rmModel.Html.DropDownList(m => m.adultsDrp, new { #class = "full-width" },"Text","Value").Value(m=>m.adultscount)
</div>
</div>
<div class="col-xs-3">
<label>KIDS</label>
<div class="selectorgen">
#rmModel.Html.DropDownList(m => m.childDrop, new { #class = "full-width" }, "Text", "Value").Value(m => m.childcount)
</div>
</div>
<div class="agecls">
#using(var chage=rmModel.Foreach(m=>m.childage))
{
<div class="col-xs-3">
<label>Child</label>
<div class="selectorgen">
#chage.Html.DropDownList(m => m.ageDrop, new { #class = "full-width" },"Text","Value").Value(m=>m.Age)
</div>
</div>
}
</div>
</div><hr>
}
</div>
<button type="submit" class="full-width uppercase">Search Cheap Hotels</button>
</div>
}
</form>
</div>
</div>
I believe that when the redirection did not happen then on else part your view model binding is causing your dropdown value to get changed and hence the dropdown on change event triggers again and again. Make sure you are not changing the selected item of your dropdown from ajax call.

Jquery function not called when called on modal pop up submit button in partial view in ASP.net MVC

I want to call jquery function on Modal popup submit button, which is in partial view but the function is not called if that button is in partial view, it is only called when i put my modal pop up in main view. How to solve this issue... Please help .. Thanks
Index.cshtml
#Html.ActionLink("Create", "Create", null, null, new { id = "btnCreate", #class = "btn btn-small btn-info" })
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$('#btnCreate').click(function () {
alert("function called");
$('.modal-dialog').load(this.href, function () {
$('#ShowModalDialog').modal({
backdrop: 'static',
keyboard: true
}, 'show');
});
return false;
});
});
</script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$('#Useremail').blur(function () {
alert("func called");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Search',
data: "{'searchString':'" + document.getElementById('Useremail').value + "'}",
async: false,
success: function (response) {
alert("Record found");
},
error: function () { alert("record not found"); }
});
});
});
</script>
<div id='ShowModalDialog' class='modal fade in'>
<div class='modal-dialog'>
</div>
</div>
</body>
</html>
_Create.cshtml PartialView
#model MvcTwitterBootstrap.Models.UserDetail
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<h3 id="myModalLabel">
Registration</h3>
</div>
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class = "modal-form" }))
{
#Html.ValidationSummary()
<div class="modal-body">
<div>
#Html.LabelFor(x => x.UserEmail)
#Html.TextBoxFor(x => x.UserEmail, new { #id = "Useremail" })
#Html.ValidationMessageFor(x => x.UserEmail)
</div>
<div>
#Html.LabelFor(x => x.UserPassword)
#Html.TextBoxFor(x => x.UserPassword, new { id = "Userpassword" })
#Html.ValidationMessageFor(x => x.UserPassword)
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">
Cancel</button>
<button class="btn btn-primary" type="button" id="btnsubmit">
Save</button>
</div>
}
</div>
for items that are added to the form after load you need to put the function on the document instead of the item
$(document).on('click', '#btnCreate', function(){
//code
});
the other option would be to put all of the click events in a function
function LoadScript(){
//jquery code here
}
and then call that function after the partial is loaded
$('#divContent').html(result);
LoadScript();

Categories

Resources