I have a registration form and i want to do some thing like this: When user register and enter the username then check on database that this user is already in database or not.That's why when user enter username and move to another field then check it.
So please help me how to solve this and how use textbox events.
As you have not provided any markup i'm assuming the markup like this.
<form id="form1" action="~/something.aspx" method="post">
<label>Username</label>:
<input type="text" id="username" name="username" onblur="validate();"/>
<br/>
<label>Password:</label>
<input type="text" id="password" name="password"/><br/>
<input type="submit" value="submit"/>
</form>
The basic idea is that you need to write some javascript for username field when the focus is out(onblur event)
Here is the javascript for the above piece of code.
<script type="text/javascript">
function validate()
{
//make an ajax call to retrieve the username
$.ajax({
url:'validate.aspx/ValidateUsername',
dataType: 'json',
//... make necessary adjustments in ajax call so as to
//call the web method in validate.aspx page
success: function(data){
if(!data.d){
alert('username already exists !');
document.getElementById('username').focus();
}
}
});
}
</script>
Now defined your webmethod for the ajax call defined.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ValidateUsername()
{
//Now query the database to check if the username exists.
//If the username exists return 'true' other wise return 'false'
}
Hope this helps.
This is best done using AJAX rather than server-side events, this means you can POST asynchronously for a better UX e.g.
<script type="text/javascript">
var lookupTimer;
$('#username').change(function() {
clearTimer(lookupTimer); // cancel previous lookup if user types again
lookupTimer = setTimeout(function() {
$.post("myServer/checkUsername", { data: $(this).val() }, function(result) {
// handle result
});
}, 1000); // send query after 1 second when user finished typing
});
</script>
<input id="username" type="text" />
Related
In my View i have the following code:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
Download
In my Control i have de following code:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
In this particular case, i want to pass the createdDate value that is inside the textbox (createdDate) to my Url.Action(...), so it could be passed as a queryString in my URL.
This action is invoked as a GET request, and in GetRoomAccessHistory control method, i should get my createdDate.
Thank you.
PS
I think the solution should be something like this:
<a href="#Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
I have got a possible answer:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
This does exactly what i want and it works, but i was trying to find a more nice solution because my experience in ASP.NET MVC is low.
You're using the wrong tool for the job.
Since the Url.Action() helper runs on the server-side, it has already executed when the page was first loaded, and generated a fixed URL which is inserted into the page's HTML. It cannot know what the user later enters into the textbox.
If you want to capture data which a user has entered, it makes more sense to use a form. In this case I've used the BeginForm tag helper to generate a suitable HTML <form> tag:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
When submitted, this will generate a GET request to the GetRoomAccessHistory action's URL, and append createdDate as a querystring variable, using the value from the textbox.
For Get request,try to use window.location.href.
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
And your solution could be simplified to
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>
I have an issue where the hidden values in a form are not updating when the new ActionResult is returned.
For example, a user will check several records and click the Update Completion button. This makes an Ajax called to the UpdateCompleted action that sets a date for the checked records and once the Ajax call returns the form is submitted. After performing some logic in the form submit Action method, an updated model is returned with the IsChecked value set to false for all records in the model, but the form is retaining the previous checked value due to the generated id below having the same value.
Code
<td>
#Html.CheckBoxFor(model => Model.WorkOrderDetails[x].IsChecked)
#Html.HiddenFor(modelItem => Model.WorkOrderDetails[x].IsChecked)
#Html.HiddenFor(modelItem => Model.WorkOrderDetails[x].WorkOrderEntityId)
#Html.HiddenFor(model => model.WorkOrderDetails[x].WorkOrderId)
</td>
Rendered HTML
<td>
<input data-val="true" data-val-required="The IsChecked field is required." id="WorkOrderDetails_0__IsChecked" name="WorkOrderDetails[0].IsChecked" type="checkbox" value="true"><input name="WorkOrderDetails[0].IsChecked" type="hidden" value="false">
<input id="WorkOrderDetails_0__IsChecked" name="WorkOrderDetails[0].IsChecked" type="hidden" value="False">
<input id="WorkOrderDetails_0__WorkOrderEntityId" name="WorkOrderDetails[0].WorkOrderEntityId" type="hidden" value="ODU=">
<input id="WorkOrderDetails_0__WorkOrderId" name="WorkOrderDetails[0].WorkOrderId" type="hidden" value="NjQ4OTU3">
</td>
Submit Code
#using(#Html.BeginForm("Index", "WorkOrderMaster", FormMethod.Post, new { id = "workOrderMasterForm" }))
{
<div>
<div class="project-buttons">
<div class="btn-group">
<input id="submitCompletion" class="btn btn-success" value="Update Completion" data-submit-url='#Url.Action("UpdateCompleted", "WorkOrderMaster")' />
</div>
</div>
$(function () {
$('#submitCompletion').click(function () {
$.ajax({
type: 'POST',
url: $(this).data('submit-url'),
data: $('#workOrderMasterForm').serialize(),
success: function (data) {
$('#workOrderMasterForm').submit();
}
});
});
});
I would expect the new values from the model to be used but this is not occurring.
Is it recommended to code the input values manually in this situation in order to avoid the following format?
ClassName_Index_PropertyName
Thanks in advance for the time you took to look at this question.
Based on the provided code, you are performing an AJAX call to the server but expects the values to be cleaned up after the operation is finished.
It will not work since you are not refreshing the page. To clean up the form values without refreshing the page you need to do a small change in your code:
$(function () {
$('#submitCompletion').click(function () {
$.ajax({
type: 'POST',
url: $(this).data('submit-url'),
data: $('#workOrderMasterForm').serialize(),
success: function (data) {
$('#workOrderMasterForm').reset();
}
});
});
});
The change is in the success promise where "$('#workOrderMasterForm').sugmit();" changed to "$('#workOrderMasterForm').reset();".
In an effort to keep moving on this. I moved the form to a partial view, and added a div to load the partial view into. Anytime an event fires on the page thru many filters or the users submitting checked records the div is cleared and reloaded. This solved my issue.
I have a very weird problem. Let's say I have two same forms/widgets on the same page , this is the code for the form:
<form>
<input class="form-group" type="text" title="FirstName" name="FirstName" id="FirstName" /><br />
<input class="form-group" type="text" title="LastName" name="LastName" id="LastName" /><br />
<input class="form-group" type="tel" title="PhoneNumber" name="PhoneNumber" id="PhoneNumber" /><br />
#Html.DropDownListFor(m => m.HearingID, Model.Hierings, new { #id = "HearingID", #class = "form-group" })<br />
#Html.DropDownListFor(m => m.ConnectTypeID, Model.ConnectTypes, new { #id = "ConnectTypeID", #class = "form-group" })<br />
<input type="button" value="Save" id="#buttonid" />
</form>
And the following js sends an ajax request.
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function (e) {
debugger;
e.preventDefault();
var form = $("form");
$.ajax({
type: "POST",
url: jQuery(location).attr('pathname') + '/Save/',
data: form.serialize(),
error: function (xhr, status, error) {
alert("Error");
},
success: function (e) {
}
});
});
return false;
});
</script>
By the laws of logic it should send the post request one time, but for some weird reason the number of calls correlates with the number of forms on the page. So if I have two forms - it sends the request two times. I tried everything, even giving the form a unique id, and yet still - two requests. The JS isn't working two times, the JS works one time but it still sends the request two times, and I can't figure out why.
I think you should give your form a unique ID which is generated on the server. In this way, when you drag your widget twice on the page, it will be rendered with different IDs, and moreover the jQuery selector will look for the form with the right ID. Following is a sample code of how I managed to get only one submit when I drag the widget two times on the page:
#{
// generate ID on the server
string formId = System.Guid.NewGuid().ToString();
}
<form id="#formId">
...
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#' + '#formId').submit(function (e) {
// code here
});
});
</script>
I am attempting to call a function through a view using jquery.. originally i was using razor's #html.BeignForm but for the web it needs to be converted to jquery
i don't know if i'm on the right path, however this is what i have in razor that's currently working.
#foreach(var up in Model)
{
#up._id
using (#Html.BeginForm("DQPost", "Disqus", new { ID = up._id }, FormMethod.Post))
{
<h7>The thread ID</h7>
<input type="text" name="ThreadID" /><br />
<h7>The message </h7>
<input type="text" name="Message" /><br />
<input type="submit" value="Post Comment"/>
}
}
what i'm trying to do is change the submit to button that then fires off the jquery. and this is the jquery i currently have written out.
<script type="text/javascript">
$(document).ready(function () {
$('#post').click(function () {
var dataToSend = { ID: ID, MethodName: 'DQPost', Message: message };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
});
});
</script>
any help would be greatly appreciated.
You are wrong here,$('#post').
$('#post').click(function () {
Post is not an identifier., so, you could declare your own. You could try something like
<input type="submit" id="submitButton" value="Post Comment"/>
Then,
$('#submitButton').click(function () {
will work fine.
Looks like you want to intercept the form submission so you can handle submit yourself with AJAX. If I'm reading that right, instead of attaching to the button's event, attach to the form's event:
$("#my-form-id").submit(function() {
// do my AJAX stuff
return false; // this will prevent the form from being submitted like normal
});
I have the following code which basically is a checkbox that causes a submit to take place.
As the task gets deleted for the DB, it is a requirement that some box comes up and says, "are you sure" or the likes, to confirm deletion.
<input type="checkbox"
onclick="location.href='#Url.Action("Complete", "Tasks",
new { TaskID = item.TaskID })'" />
This uses Razor syntax.
You could use the confirm method:
<input type="checkbox" onclick="if (confirm('Are you sure?')) { window.location.href = '#Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })'; }" />
or in a more unobtrusive way with jquery:
<input type="checkbox" id="complete" name="complete" data-url="#Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })" />
and then in a separate javascript file:
$(function() {
$('#complete').click(function() {
if (confirm('Are you sure?')) {
window.location.href = $(this).data('url');
}
});
});
Also I would very strongly recommend you using another verb than GET on controller actions that modify state on your server such as marking a task as completed. PUT, POST and DELETE are good candidates. In your case since you are modifying an existing item the POST verb seems most natural.
You may intercept the form submit event and ask confirmation. based on that return true or false to allow submit.
akin
$("#form").submit(function (event) {
if ( confirm("Are you sure you want to delete"))
return true;
else{
event.preventDefault();
return false;
}
});
It can be done this way
<input name="button" type="submit" value="Delete" class="btn btn-danger cancel" onclick="return confirm('Are you sure?')" />
hemant's solution didn't work for me. Moumit's solution did work but not when I moved the confirmation function to a named function in my page's javascript file - the confirmation button displayed but it was not prevented when I hit cancel (and as I write this, I wonder if I only needed to pass an event arg, call e.PreventDefault(), then return true).
Anyhow, here is yet another example, with a little help from JQuery, that did work in my aspnetcore mvc razor page:
$(function () {
$('#mySaveButton').click(function (e) {
e.preventDefault();
if (confirm('Are you sure?')) {
$('#myForm').submit();
}
});
});
I adapted this from a more complete example that is worked out from start to finish with an example project: how to show a confirmation dialog with jquery