After show Modal Window jQuery validation plugin doesn't work - javascript

I have a problem with jQuery Validation Plugin.
I used ASP.NET MVC with Entity Framework. The project has a lot of libraries and it's hard to understand the problem and find answer.
I have a form on which the section with fields. I used validation plugin for validate client-side fields.
The section is collapsible and can to be open and closed. Inside section I have button for open modal window. Inside window I can to search data used Ajax. User can to add information manually, can add information used Ajax and fields can be empty.
The first task is to add validation for hidden fields.
I added setDefault for validator inside $(document).ready:
jQuery.validator.defaults.ignore = "";
When I added setting ignore for validator, everything work fine with hidden fields and open fields but after showing modal window validator plugin doesn't work. In FireBug I take error: TypeError: validator is undefined (twice).
I open and close the modal window (without Ajax search) and I take this error and validator doesn't work.
This is modal window code:
#using (modal.BeginBody()){
<div class="row">
<div class="col-lg-offset-3 col-lg-6" id="search-entry-form">
#using (var form = Html.Bootstrap().Begin(new Form().HtmlAttributes(new { onsubmit = "return false" })))
{
#form.FormGroup().TextBoxFor(model => model.EANCode).Label();
#form.FormGroup().TextBoxFor(model => model.Name).Label();
#form.FormGroup().TextBoxFor(model => model.InternationalName).Label();
#Html.Bootstrap().Div(Html.Bootstrap().SubmitButton().Text("Wyszukaj").Id("search-specific").Style(ButtonStyle.Success).
ButtonBlock().PrependIcon("glyphicon glyphicon-search")).Class("col-lg-5 col-lg-offset-7");
}
</div>
</div>
<div class="col-lg-12 top30" id="result-table"></div>}#using (modal.BeginFooter()){#Html.Bootstrap().Button().Text("Zamknij").Data(new { dismiss = "modal" }).Style(ButtonStyle.Primary)}
I this file I added Bundels with Ajax code:
#Scripts.Render("~/bundles/specificNutSearch")
This is Ajax code:
$(document).ready(function () {
function pagination() {
$('#result-table').each(Utils.Pagination);
}
function getData(id) {
$.ajax({
url: "GetSpecific",
dataType: "json",
method: "POST",
cache: false,
data: {
id: id
},
}).success(function (result) {
if (result === null) return;
for (var propName in result) {
$(".panel [Name$='." + propName + "']").val(result[propName]);
}
clear();
});
}
function clear() {
$("#result-table").html("");
$(".modal input").val("");
$(".pager").remove();
}
function search() {
var form = $("#search-entry-form :input").serialize();
$.ajax({
url: $('#search-entry-form form').attr('action'),
dataType: "html",
method: "POST",
cache: false,
data: form
}).success(function (result) {
$("#result-table").html(result);
$(".select-specific").on("click", function () { getData($(this).data("specific")) });
pagination();
});
}
$("#search-specific").on("click", search);});
This is the field code which need validate:
Html.Bootstrap().Div(
Html.Bootstrap().Label("").LabelText("4.").Class("pull-left"),
Html.Bootstrap().FormGroup().TextBoxFor(model => model.EAN).Label()).Class("col-lg-6")
In the chhtml view I added modal window on the bottom file:
<div class="modal fade" id="specificNutritionalPurposeSearch" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
It is ViewModel field:
[Display(Name = "Kod EAN")]
[RegularExpression("[0-9]{13}",ErrorMessage = "Kod EAN powinien zawierać 13 znaków")]
public string EAN { get; set; }
Also found a very strange thing:
When I Comment out the all specificNutSearch (#Scripts.Render("~/bundles/specificNutSearch")) code, the plugin does not work.But when I comment out #Scripts.Render("~/bundles/specificNutSearch" line, plugin works.
What could be the problem? Maybe that's a problem of incompatibility of versions jQuery and Validator Plugin?
EDIT:
This is button code for open model window:
#Html.Bootstrap().Button().Text("Wyszukaj środek spożywczy").TriggerModal("specificNutritionalPurposeSearch").HtmlAttributes(new { href = Url.Action("SearchSpecificNutritionalPurpose") }).Style(ButtonStyle.Success).ButtonBlock().PrependIcon("glyphicon glyphicon-search")
This is ActionResult in Controller:
[HttpGet]
public ActionResult SearchSpecificNutritionalPurpose()
{
var model = new SpecificNutritionalPurposeSearchViewModel();
return PartialView("Modals/_SpecificNutritionalPurposeDictionarySearch", model);
}
In action model empty because modal window has button for searching data.
This is ActionResult for search button in modal window for searching data:
[HttpPost]
public virtual ActionResult SearchSpecificNutritionalPurpose(SpecificNutritionalPurposeSearchViewModel searchParameters)
{
var searchResult = _dictionaryRepository.FindSpecificNutritionalPurpose(searchParameters.EANCode, searchParameters.Name, searchParameters.InternationalName).Take(100).ToList();
return PartialView("Modals/_SpecificNutritionalPurposeSearchResult", searchResult);
}
Method FindSpecificNutritionalPurpose take data from dataBase (EF)

I think that when the specyficNutSearch script alters the DOM the validation handlers are getting removed.
My solution is to change clear method so it will refresh validation handlers:
function clear() {
$("#result-table").html("");
$(".modal input").val("");
$(".pager").remove();
//add this
var $form = $("#search-entry-form form");
$form.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($form);
}

Related

How do I insert a PartialView into a normal View using an Ajax-Function in ASP.NET Core 3?

This is the site.js code I am using to insert the PartialView into the main View.
$("#btn2").click(function () {
$.ajax({
url: "/Home/RefreshDoors",
datatype: "text",
type: "POST",
success: function (data) {
$('#DoorBox').html(data);
},
error: function () {
$("#DoorBox").html("ERROR");
}
});
});
I want to place the resulting table inside a box (div with the id="DoorBox") however as a result I get a raw view of the returned Door-Json-Objects:
(imgur-link to screenshot)
This is the div-code inside the view:
<div id="DoorBox">
</div>
This is the code from the HomeController I use to render the PartialView:
[HttpPost]
public PartialViewResult RefreshDoors()
{
return PartialView("_Doors", RefreshDoorsFunction().Result);
}
How do I get the code to insert the PartialView (just a table with the properties of the door-model displaying the doors)) to render within the div-box (without refreshing the page)?
Edit: Here is the code from the RefreshDoorsFunction():
public async Task<List<NewDoor>> RefreshDoorsFunction()
{
string token = await _auth.GetTokenAsync();
_doorList = SecureRestCall.GetDoorListAsync("https://exampleapi.azurewebsites.net", token);
return _doorList.Result;
}
I got the answer. Turns out I'm just stupid: I used the wrong button to test the ajax function (wrong id assigned to the button). It works now. Sorry for wasting some people's time.

Modal Popup not loading in partial view when calling from parent view

I am trying to call a modal on a partial view from a view but am not getting ajax success call, but dont know how to do it:
Here is what i have, javascript ajax code on my page:
var TeamDetailPostBackURL = '/BMApproval/GetMeetingApprovalData';
$(function () {
$(document).on('click','.LeadCode', function () {
//$(".LeadCode").click(function () {
debugger;
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
alert("load");
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "dataValue": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
And parameters I am passing in ajax call
<td>#LPOPoint.LeadCode</td>
Also calling modal popup in the same javascript page which will popup on the partial view.
<div id='myModal' class='modal' style="overflow-y:hidden;">
<div class="modal-dialog" style="overflow-y: scroll; max-height:85%; margin-top: 20px; margin-bottom:20px;">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div></div>
I searched a lot in various forums but couldn't get any solution.
When am clicking on html link the popup doesn't load in the partial view.
And ("Dynamic content load failed."); is displayed as it doesn't get to success.
Basically I want to view data in modal popup in partial view based on the parameters from parent view. Any help would be appreciated.
At the first sight looks like you need TeamDetailPostBackURL variable to contain a proper URL including scheme, host (and port if needed) like 'http://example.com/BMApproval/GetMeetingApprovalData'
You can specify error parameter in the error callback to see what exactly is wrong
error: function (error) {
console.error(error)
alert("Dynamic content load failed.");
}

How to set a Model property inside javascript and be able to receive it in POST method

I have a button when that button is clicked I want to set a model property to true and be able to receive it in the back end. Code is a bit messed up but bear with me please as I have taken alot of code out of it.
#model FullConfigurationMV
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "MyForm" }))
{
#Html.HiddenFor(model => model.IsTemplate)
// Code removed for brevity
<button id="DraftName">Click me</button>
}
<script>
$( document ).ready(function() {
debugger;
$("#DraftName").click(function()
{
#Model.IsTemplate = true; // I AM SETTING THE VALUE AS TRUE
SaveStyles();
});
});
</script>
<script>
function SaveStyles() {
var data = $('#MyForm').serialize();
var URL = "SOME URL"
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
},
error: function (error) {
}
});
}
</script>
POST ACTION
public JsonResult SaveStyles(FullConfigurationMV data)
{
// data.IsTemplate is coming out to be false
// Rest of the UI control data is coming back properly
}
EDIT
Since I have below code. is that the issue?
var data = $('#MyForm').serialize();
Think about this problem a little differently.
All the view does is render html. Since you have a form in html, all your javascript has to do is to set the form element's value to true.
You should be able to use the jQuery selector like
$('input:hidden[name=IsTemplate]').val(true);
And your form serialize should pick it up.
Razor view are generated in server side. So when you browser get the HTML there is no razor code in it so the following code will not work:
$("#DraftName").click(function()
{
#Model.IsTemplate = true; // <-- this will not work and will not exist in client side
SaveStyles();
});
You should set the hidden field you just put in your form #Html.HiddenFor(model => model.IsTemplate) which generate <input type='hidden' /> and just update your javascript code by doing this:
$("#DraftName").click(function()
{
$("#MyForm input[type='hidden']").val("true"); // <- Replace your Razor code with this.
SaveStyles();
});

Asp.net MVC-5 working with bootstrap toggle switch

I am working on asp.net MVC 5, referring to my question i have added a bootstrap toggle switch in my page, the razor syntax is bellow
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>
}
This razor syntax is placed in a partial view and is called in a layout
The generated Switch button is as follows
Now, i want to pass this On or Off value(string) to my action method.
For start i have placed a javascript event function and which simply shows me the alert box displaying On or Off with respective switch condition
My script is as follows
<script>
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
alert("ON");
} else {
alert("Off");
}
}); </script>
For passing this On or Off i have searched many articles and found that ajax call is used for this purpose so i placed a ajax call in my if and else condition
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
data: '{"cmdName": "On"}',
success: function (data) {
alert(data);
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
data: '{"cmdName": "Off"}',
success: function (data) {
alert(data);
}
});
}
Bellow is my action method
public ActionResult MultiGraph(string search, string start_date, string cmdName , string End_date,int? page)
{
// i want to pass On or Off values based on switching in my string cmdName
}
Is there any other way rather than ajax call to do it? Or what should i do in my ajax call ?
Updated Code
In my script i have done the following
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
//alert("ON");
var data = { cmdName: "On" }
} else {
//alert("Off");
$.ajax({
url: '#Url.Action("MultiGraph")',
data: data,
});
}
});
See the bellow images
Getting null in cmdName
I am unable to pass them, i must be missing some thing which i don't know
Any help would be appreciated

Using Jquery ajax to call ActionResult method in Controller and return data

I'm trying to understand how the Jquery Ajax methods works. Right now, I have some problems calling the ActionResult method in the controller that will return a PartialView.
Have created an button which I will use to get new data in from the server (Ajax call should run)
Code: (ActionResult in Home controller)
public ActionResult All()
{
List<Student> model = db.Students.ToList();
return PartialView("_Student", model);
}
This method is the one I'm trying to call when I press the button in the main Index view.
Code: (Index view)
<div class="row">
<div class="small-12 column sbw-travel">
<h2>Travel</h2>
<div class="row">
<div class="small-12 columns">
<button id="button1" class="sbw-travel-button">Search</button>
</div>
</div>
<div class="small-12 sbw-travel-box" id="rooms">
</div>
</div>
</div>
When the user hit the button, an Ajax call should run, and the list will appear in the section with id=rooms.
Script: (Ajax code)
$(document).ready(function () {
$('#button1').click(function () {
$.ajax({
type: 'GET',
url: #Url.Action("All", "Home"),
datatype: "html",
success: function () {
$('#rooms').html(???);
}
});
return false;
});
});
Can any of you see if I have forgot something to make this run like I have described?
The result is on the succes event. Try:
$(document).ready(function () {
$('#button1').click(function () {
$.ajax({
type: 'GET',
url: #Url.Action("All", "Home"),
datatype: "html",
success: function (data) {
$('#rooms').html(data);
}
});
return false;
}); });
I would suggest loading firebug when you click the button (enable the console), make sure the requested URI is responding with valid HTML data on the click event.
I also generally find using something like:
$('#button1').on('click', function () { ...
usually yields better results, see here: Difference between .on('click') vs .click()

Categories

Resources