How do i fire validation message on Button click instead of Submit button - asp.net-mvc-3

I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)

you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.

I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>

Related

my ajax not giving result in codeigniter

i am registering users via ajax, user is inserted into the database but my loader continue to show loading and is no hiding furthermore i put an alert to view the result but it is also not shown
so where i am doing wrong please help me.
here is my view
<tr>
<td style="width: 25%;"><p>Name</p>
<input type="text" name="name" id="name_r"
placeholder="Enter name" required=""/>
</td>
<td style="width: 25%;"><p>username</p>
<input type="text" name="username" id="uname"
placeholder="Enter username" required=""/>
</td>
</tr>
my script is
$(document).ready(function(){
$("#register_staff").click(function(){
var name = $("#name_r").val();
var username = $("#uname").val();
if (name && username) {
$('#loader_register').show();
$.ajax(
{
type: "POST",
url:"<?php echo
base_url('register_management_staff')?
>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
}
);
}
else{
document.getElementById
('result_register').innerHTML='<font color=red>
Please fill all fields.</font>';
}
});
});
my controller is
public function register_management_staff()
{
$post['name']= $_REQUEST['name'];
$post['username']= $_REQUEST['username'];
$result = $this->managementmodel
->register_management_staff($post);
if($result == 1){
echo '<font color=green>Congrats! Successfully
Register.</font>';
}
else{
echo '<font color=red>Please enter correct data
and check availability.</font>';
}
}
my model is
public function register_management_staff($post)
{
$this->db->insert('management_login',$post);
return 1;
}
If you have a button by the id of register_staff then >
Edit Your Script and Use This
$(document).ready(function(){
$("#register_staff").on('click',function(){
var name = $("#name_r").val();
var username = $("#uname").val();
if (name && username) {
$('#loader_register').show();
$.ajax({
type: "POST",
url:"<?php echo base_url('register_management_staff'); ?>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
});
}
else{
$('#result_register').html("<font color='red'>Please fill all fields.</font>");
}
});
});
In your ajax code provide correct path in url
$.ajax(
{
type: "POST",
url:"<?php echo
site_url('register_management_staff')?
>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
}
);
Here in ajax url must be like
url:"<?php echo site_url('controller_name/method');?>"
Make changes are try

hide bootstrap modal after select redirect instead

I would like to close my modalbox, so I return to the same page, after I click the "Select" button.
I am on shuffle.php. I open the modalbox and call the code in updaterecords.php. When I click Select I should return to shuffle.php. The problem is right now that I am redirected to updaterecords.php.
I try to solve that with adding this code to my AJAX call:
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
But I am still redirected. Is the code I added in the wrong place?
shuffle.php
<div class="modal-footer msg">
<form action="updaterecords.php" method="post">
<input type="hidden" id="fantasy-id" value="" name="id" />
<button type="submit" name="selectStore" >Select</button>
<button type="button" data-dismiss="modal">Close</button>
</form>
</div>
updaterecords.php
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
Please try to use $('.modal').modal('hide'); on updaterecords.php.
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$('.modal').modal('hide');
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});

SOAP webservice call to a method using jquery ajax that sends 2 parameters, how to catch the responses in a loop

I have a SOAP webservice created in c# (hosted on localhost) called soapService.aspx . It has a method called displayClass(String id, String theDate)
it returns. This returns following json
[{"lesson_id":2,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":"11:22","end_time":"14:22 ","notes":"test test","payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":3,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":4,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3}]
I found this using web service invoke method given on the web service description page.
I want to catch the response using ajax.
So far I wrote this
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data:instructorInput,
contentType:"application/json; charset:utf-8",
success:function(msg){
//process the msg
}
});
}
});
1) How do I invoke the web service method by passing parameters
2) How do i display all these json data in a table? Please help
Edit : Tried to post
data: "{'id': '" + instructorInputID + "','theDate': '" + instructorInputDate + "'}",
THis is the response I get from console
XMLHttpRequest cannot load http://localhost:18324/soapService.asmx/displayClasses. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:17182' is therefore not allowed access.
EDIT Two :
complete code : Still Error.. msg not defined
<pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#findClassBtn").click(function () {
displayClass();
});
function onSuccess(msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "soapService.asmx/displayClasses",
type: "POST",
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: onSuccess(msg)
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="Label1" runat="server" Text="Add Your Id"></asp:Label>
<p>
<asp:TextBox ID="instructorIdText" runat="server"></asp:TextBox>
</p>
<asp:Label ID="Label2" runat="server" Text="Add date (dd/mm/yyyy)"></asp:Label>
<p>
<asp:TextBox ID="instructordateText" runat="server"></asp:TextBox>
</p>
<asp:Button ID="findClassBtn" runat="server" OnClick="findClassBtn_Click" Text="Find Classes" />
<p>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</p>
</form>
<table id="table">
</table>
<pre>
Error: msg is not defined.
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: function (msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
</table>

update model with ajax in razor

i write this code with ajax to delete some info after that i update my updateAjax div with ajax for refreshing content and this view have masterpage.in picture u see what happen.
this is my code
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
<div class="btnContainer">
delete
<br />
<br />
</div>
<script>
$(function () {
// function for delet info and update #updateAjax div
$("#DeleteUser").click(function (event) {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
$.ajax({
url: '#Url.Action("DeleteUser", "UserManagement")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: JSON.stringify(list),
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
// window.location.reload()
},
error: function (data) {
//$('#updateAjax').html(data);
window.location.reload()
}
}); //end ajax
});});
</script>
</form>
this my controller code
public ActionResult View1()
{
ViewBag.PageTittle = "user list";
ViewBag.FormTittle = "user list";
SetUserManagement();
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View(Result.Data);
}
else
{
return View(new VwUser());
}
}
public ActionResult DeleteUser(string[] userId)
{
SetUserManagement();
string message = "", CssClass = ""; ;
foreach (string item in userId)
{
//TODO:show Message
var Result = userManagement.DeleteUser(int.Parse(item));
if (Result.Mode != Common.Extensions.ActionResultMode.Successfully)
{
var messageResult = XmlReader.FindMessagekey(Result.Mode.ToString());
message += messageResult.MessageContent + "<br/>";
CssClass = messageResult.cssClass;
}
}
if (string.IsNullOrEmpty(message))
{
SetMessage(Common.Extensions.ActionResultMode.Successfully.ToString());
}
else
{
ViewBag.MessageResult = message;
ViewBag.cssClass = CssClass;
}
//
{
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View("~/Views/UserManagement/View1.cshtml", Result.Data);
}
else
{
return View("~/Views/UserManagement/View1.cshtml", new VwUser());
}
}
}
It looks to me that your view ViewUserList.cshtml is using a Layout that would either be set through Layout or through the _ViewStart.cshtml file. Make sure you're not using any of these.
For disabling the use of your Layout, you could take a look at this question. Or just set Layout = null

Passing Id from javascript to Controller in mvc3

How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '#Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller
instead of
$.post(url,data, function (result) {
// });
My View
#using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { #id = "myAjaxForm" }))
{
<table id="tblclick">
#for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='#Model.names[i].Id'>
#Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { #id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
I would avoid using the Ajax Beginform helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
#foreach(var name in Model.names)
{
<tr>
<td id="#name.Id">
#Html.ActionLink(name.Name,"listpage","yourControllerName",
new { #id = name.Id },new { #class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load function to load the response from thae listpage action method to the div with id showPage.
Assuming your listpage action method accepts an id parameter and returns something
I am not sure for $.post but I know window.location works great for me.
Use this instead and hopefully you have good results :)
window.location = "#(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Just use a text box helper with html attribute ID.
#Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});

Resources