Infinity Ajax Request When Drop Change in Knockout MVC - javascript

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.

Related

How do I get the values of a BeginCollectionItem in javascript

I want to get values of a BeginCollectionItem using javascript but it seems like i am not winning
my html
#using HtmlHelpers.BeginCollectionItemCore
#using E_Commerce.Application.Models
#model ProductImageModel
<li class="mb-2">
#using (Html.BeginCollectionItem("ProductImages"))
{
Html.RenderPartial("_imagesPartial", Model);
}
</li>
the _imagesPartial html
#model E_Commerce.Application.Models.ProductImageModel
<div class="col-md-12 row mb-2">
<div class="col-md-4 imageDiv">
<img class="border rounded" />
</div>
<div class="col-md-4">
<input type="file" asp-for="File" onchange="uploadImageTest(this)" />
</div>
<div class="col-md-4">
Remove
</div>
</div>
and my javascript
let addNewImagesFormSubmit = (event) => {
var Id = $("#Id").val();
var productImages = $("#ProductImages").val();
$.ajax({
url: "#Url.Action("AddNewImages","ProductImage")",
data: {
Id: Id,
productImages:productImages
},
success: function (data) {
$("#productImagesDiv").html(data);
}
})
}
the server side does not seem to get any images when using javascript to get the BeginCollectionItem.
how do i get it to work

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>

Ajax Success does not render partial view

I have placed a partial view into a modal to update a password like so:
<div class="modal fade" id="modalPassword" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-body">
<div class="modal-content">
<div id="message"></div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Change Password</h4>
</div>
<div class="modal-
<div id="passwordForm">
#{
#Html.Action("ChangePassword","Account");
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is my partial view:
#model WebApplication1.Models.ViewModel.ChangeUserPassword
#{
Layout = null;
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<form id="form">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset id="submitPasswordForm">
<div class="col_full">
#Html.LabelFor(model => model.OldPassword, htmlAttributes: new { #class = "capitalize t600" })
#Html.TextBoxFor(model => model.OldPassword, null, new { #class = "sm-form-control", id = "txtOldPassword" })
#Html.ValidationMessageFor(model => model.OldPassword)
</div>
<div class="col_full">
#Html.LabelFor(model => model.ChangedPassword, htmlAttributes: new { #class = "capitalize t600" })
#Html.TextBoxFor(model => model.ChangedPassword, null, new { #class = "sm-form-control", id = "txtChangedPassword" })
#Html.ValidationMessageFor(model => model.ChangedPassword)
</div>
<div class="col_full">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "capitalize t600" })
#Html.TextBoxFor(model => model.ConfirmPassword, null, new { #class = "sm-form-control", id = "txtConfirmPassword" })
#Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<input type="submit" value="Save Changes" class="btn btn-primary" id="btn_save_password" />
</div>
</fieldset>
</form>
When I click the "btn_save_password", I invoke the onclick event like so:
$("#btn_save_password").click(function (event) {
event.preventDefault();
var data = $("#submitPasswordForm").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("ChangePassword", "Account")",
data: data,
success: function (result) {
$("#passwordForm").empty();
//$("div").remove("#passwordForm");
addHtml(result);
},
error: function () {
$("#passwordForm").html("Error occured");
}
});
});
function addHtml(htmlString) {
$("#msg").html(htmlString);
}
Then it invokes a method in my controller "ChangePassword"
[Authorize]
public ActionResult ChangePassword()
{
return PartialView();
}
[HttpPost]
public ActionResult ChangePassword(ChangeUserPassword password)
{
if (ModelState.IsValid)
{
var cookie = HttpContext.Request.Cookies["Sys_user_id"];
var um = new UserManager();
if (cookie != null && um.GetAccountPassword(Convert.ToInt32(cookie.Value), password.OldPassword))
{
um.ChangeUserPassword(password, Convert.ToInt32(cookie.Value));
}
else
{
ModelState.AddModelError("","Wrong current password");
}
}
else
{
ModelState.AddModelError("","Error");
}
return View();
}
The "ChangePassword" method invokes the PartialView "ChangePassword.html" like so:
[Authorize]
public ActionResult ChangePassword {
return PartialView();
}
I can view the partial view on the modal and I am able to successfully update the database. But the problem is, I want to be able to send a successful message or error message into the modal when it is successful or not. Upon submission, whether it has updated the database or not, it refreshes the page and the modal is gone. I want to be able to get the message into the modal.
Your help is greatly appreciated.
EDIT --
I can now see the validation message in the Modal but it only works once. As soon as I click the "btn_save_password" again, the page refreshes.
Add two <div> sections containing your messages (Successs and Failed) with the hide class in the partial view. After Ajax Submission, Add class Show for the suitable div.
eg:
<div class="alert alert-danger text-center hide" role="alert"id="FailedMesssage">
Failed....!!!
</div>
<div class="alert alert-success text-center hide" role="alert" id="successMesssage">
success....!!!
</div>
<button type = "button" value="Submit" onclick ="Test()"/>
Set Var Value as 0 or 1 using ajax code then try following script
<script>
function Test()
{
var value =1;
if(value == 1)
{
$("#successMesssage").addClass("show").removeClass("hide");
}
else
{
$("#FailedMesssage").addClass("show").removeClass("hide");
}
}
</script>

Vue js retrive new data after ajax call

I have one button when I click on this button I retrive data. But when I click second way I dont retrive new data
Here is my code
https://codepen.io/anon/pen/weobMP
Html
<button type="submit" class="btn btn-sm btn-success form-control" id="click">Filter</button>
<div class="col-md-6 cart-items" id="myjp">
<div v-for="(item, index) in items">
<div class="panel panel-info">
<div class="panel-heading" v-on:click="greet">
<h3 {{index+1}} {{item.Car}}</h3>
</div>
<div class="mojbody panel-body" v-for="tire in item.tires">
Tire: {{tire.Name}}
</div>
</div>
</div>
</div>
JS
$(function() {
var id = 1;
$("#click").click(function(){
id++;
new Vue({
el: '#myjp',
data: {
items: null
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
var self = this;
$.get('/retriveHistory',{id: id}, function( data ) {
self.items = data;
console.log(data);
});
},
}
});
})
});

.submit(function ()) inside my modal popup is not working, and my modal popup will send normal http post request

I am working on an asp.net mvc web application. on my main view i got the following create link:-
<a class="btn btn-success" data-modal="" href="/Staff/Create" id="btnCreate">
<span class="glyphicon glyphicon-plus"></span>
</a>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
and i have the following script:-
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('#myModalContent', dialog).submit(function () {
if ($('#myModalContent').valid()) {
$('#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();
alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
}
else {
return false;
}
});
}
Now when i click on the Create link the Create action method that will return the following partial view, which will be rendered inside a modal popup :-
#model SkillManagement.Models.Staff
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Staff</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.GUID, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GUID)
#Html.ValidationMessageFor(model => model.GUID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsExternal, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IsExternal)
#Html.ValidationMessageFor(model => model.IsExternal)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
//code goes here
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
till now i have every thing working well, the Get Create action method will be called and the partial view will be rendered inside a modal popup.
but now inside my partial view if i click on "Create" button , the Post create action method will be called but not due to the javascript code . and when i check Request.IsAjax() inside my Post create action method, i got that it is not an ajax request which means the partial view send a normal Post http and not ajax request as defined inside the script,, can anyone advice what is wrong in my current approach ?
Thanks
as you can see you just pass the #myModalContent node to the bindForm function, and jQuery selector looks for
// will never find #myModalContent
$('#myModalContent', myModalContentDOMElement).submit(function () {
Instead you should do something like this
$('form', dialog).submit(function (e) {
e.preventDefault(); // stop the default form submit action
You are loading your form into the page via ajax, but the form you are loading is a regular html form if you want the form itself to use ajax, I believe are looking for #Ajax.BeginForm().
msdn documentation
#using (Ajax.BeginForm({objectparams})){
...

Categories

Resources