Textbox lost focus event in MVC.NET - javascript

I am working on a MVC project and I am having few issues with textbox lost focus event.
First I have a form there are four textboxes field, on first text box we need to pass name of the employee but we have called this textbox lost focus event to populate all records of Employee if it is already in the database but I am having problem when I pass name in the textbox and clicking "save" button then first textbox event called to check if record exist in the database or not then I need to reclick button once again to save my records if not exist.
So in that case I have to click button twice.
Please help with your thoughts I do not want user to click twice.
Thanks

I would say, you may use Jquery ajax to do the work.
When the textbox focus is lost, an ajax get call will be made to the controller action which will check the DB and will return the status whether the username already exist or not.
Jquery:
$(document).ready(function () {
$("#UserName").focusout(function () {
var username = $("#UserName").val();
var fullurl = '/User/UserNameCheck?username=' + username;
if (username.length > 0) {
$.ajax({
url: fullurl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
//data: username,
success: function (data) {
if (data == 'UserNotPresent') {
$("#username_NotPresent_lbl").show();
}
else if (data == 'UserPresent') {
$("#username_Present_lbl").show();
}
else {
$("#failed_check_lbl").show();
}
},
error: function (e) {
$("#failed_check_lbl").show();
}
});
}
});
$("#UserName").focus(function () {
$("#username_NotPresent_lbl").hide();
$("#username_Present_lbl").hide();
$('#failed_check_lbl').hide();
}); });
Controller Action:
[AllowAnonymous]
[HttpGet]
public JsonResult UserNameCheck(string username)
{
Users loggedInUser = db.Users.FirstOrDefault(x => x.UserName == username);
if (loggedInUser != null)
{
return Json("UserPresent", JsonRequestBehavior.AllowGet);
}
else
{
return Json("UserNotPresent", JsonRequestBehavior.AllowGet);
}
}
View:
<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)
#Html.Label("Sorry this user name is already in use", new {id="username_Present_lbl", #class ="ErrorLbl"})
#Html.Label("User name available for use", new {id="username_NotPresent_lbl", #class ="SuccesLbl"})
#Html.Label("Failed to validate the user name", new {id="failed_check_lbl", #class ="FailedCheckLbl"})
</div>
</div>

Related

Jquery Ajax call does not call Asp.net mvc controller action method

I have two drop-downs State and City.According to State selected city should be loaded.So I use State drop-down change event to call ajax method to populate City drop-down.
HTML
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>State</label>
#Html.DropDownListFor(m => m.State, Model.States, "Please select a State", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>Cities</label>
#Html.DropDownListFor(m => m.CityRegisterScreen, new SelectList(string.Empty, "Id", "Name"), "Please select a city", new { #class = "form-control" })
</div>
</div>
</div>
JavaScript
This Contains Jquery and Javascript Code.
$(document).ready(function () {
$("#State").on("change", function () { // whenever a selection is made
$("#CityRegisterScreen").empty();
var id = $("#State").val();
$.ajax({
type: 'GET', // we are calling json method
url: '#Url.Action("GetCitiesByDistrict", "Account")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { id: id },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityRegisterScreen").append('<option value="' + city.value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
return false;
});
});
Controller
This is the controller action method which returns Json
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
Issue is when ajax method is called it doesn't call the Action method in controller.I double checked the URL and DataType it's all perfect.But Action method didn't get called.
It is silly!!! How did i miss this. Thank You #Rajshekar Reddy for your comment it guided me. I am missing [AllowAnonymous] attribute.
[AllowAnonymous]
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
This is a code for loading States according to selected country. Try this solution.
HTML
#Html.DropDownListFor(model => model.CustAddr_Country_ID, Model.Countries, "Select Country", htmlAttributes: new { #class = "disableInput", #id = "ddlstate", #onchange = "javascript:GetCity(this.value);" })
#Html.DropDownListFor(model => model.CustAddr_State_ID, ViewBag.CustAddr_State_ID as SelectList, "Select State", htmlAttributes: new { #class = "disableInput"})
Script
function GetCity(_stateId) {
$("#CustAddr_State_ID").empty().trigger('change');
var newOption = new Option("Select State", 0, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
if (_stateId != null && _stateId != "") {
var url = "/Ajax/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
for (var x = 0; x < data.length; x++) {
var newOption = new Option(data[x].Text, data[x].Value, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
}
$('#CustAddr_State_ID').val('0').trigger('change');
},
error: function (reponse) {
//alert("error : " + reponse);
}
});
}
}
Controller
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<State> objcity = new List<State>();
objcity = _state.GetState().Where(m => m.State_Country_ID == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "State_ID", "State_Name", 0);
return Json(obgcity);
}

Main view stacks on the same page after calling partial view

I have this action that returns different partial view based on the selected value from the drop down list.
Controller:
[HttpPost]
public ActionResult Foo(SomeViewModel VM)
{
var model = VM
if (Request.IsAjaxRequest())
{
if (model.SelectedValue == 1 || model.SelectedValue == 2 || model.SelectedValue == 3)
{
// ...
return PartialView("PartialView1", model);
}
else if (model.SelectedValue == 4)
{
// ...
return PartialView("PartialView2", model);
}
else (model.SelectedValue == 5)
{
// ...
return PartialView("PartialView3", model);
}
}
return View(model);
}
Main View:
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
<h2>Paint Computation</h2>
#using (Ajax.BeginForm("Foo", "Controller",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "Result"
}))
{
<div class="col-md-10">
<h5>Type of Paint</h5>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.PaintType, "Value", "Text"),
"Please Select", htmlAttributes: new { #class = "form-control" })
</div>
<br />
// Some HTML helpers
<input type="submit" value="Compute" class="btn btn-default" id="Submit" />
</div>
}
</div>
//This is how I render my partial view using jQuery in my main View:
<div id="Result">
<hr />
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#Submit').click(function () {
$('#Result').load('/Controller/Foo');
});
});
</script>
Whenever I clicked the button, the partial view appears, but when I clicked it again for the 3rd or 4th time, the main view content stacks on the same main view. I tried to use the inspect element and that's how I determined that it stacks the same main view elements.
Is my way of calling the partial view is right? As much as possible I want to use ajax for calling the partial view every time the button is clicked. Please guide me to correct it. Thanks.
Here's the of the problem.
<script type="text/javascript">
$(document).ready(function () {
$('#Submit').click(function () {
$.ajax({
type: 'POST',
url: '/Controller/Foo',
cache: false,
contentType: "application/html; charset=utf-8",
dataType: 'html',
success: function (result) {
$('#Result').html(result);
}
});
});
});
</script>
Now it works. I changed my code and use the code above. I use .html() rather than .append() or .replaceWith(). Now every time i click the button, it changes the <div id = "Result> content.

Passing user input from View to Javascript function

I have a view which asks for user input. View is as below -
#(Html.Input(m => m.SchoolName).Id("SchoolName"))
#(Html.Input(m => m.Address).Id("Address"))
#(Html.Input(m => m.Phone).Id("Phone"))
<button class="btn btn-primary" name="btnSchoolSave" id="btnSave">
Submit
</button>
Then I have a javascript function, which handles the click event of the button -
function () {
$("button[name='btnSchoolSave']").on('click', function () {
$.ajax({
url: '/School/SaveSchool', //School is my controller and 'SaveSchool' is the method in the controller.
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html'
})
.success(function (result) {
alert("saved")
})
.error(function (xhr, status) {
alert(status);
})
})
};
My Controller method is like below. I have not implemented the method yet.
public void SaveSchool(Models.School model)
{
//TODO
}
My idea is - I want to get all the values inputted by the user in the View, get all those Model values, and pass it to Javascript function and javascript function in return passes the Model to the controller method and save it.
Now, I know that I can directly call my Controller action method from the view and get the saving of data taken care of. But, my requirement is to pass the data to javascript and from javascript call the method and save user input.
How can I do that?
Thanks
#model XXX.YourViewModel
<form id="your-form" style="margin: 0px;">
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)
#Html.LabelFor(m => m.SchoolName)
#Html.TextBoxFor(m => m.SchoolName)
#Html.ValidationMessageFor(m => m.SchoolName)
#Html.LabelFor(m => m.Address)
#Html.TextBoxFor(m => m.Address)
#Html.ValidationMessageFor(m => m.Address)
#Html.LabelFor(m => m.Phone)
#Html.TextBoxFor(m => m.Phone)
#Html.ValidationMessageFor(m => m.Phone)
<button id="btnSchoolSave" name="edit" type="button">Save</button>
</form>
$("#btnSchoolSave").on('click', function () {
//get the form
var form = $("#your-form");
//validate form
if (!form.valid()) {
return;
}
//serialize the form
serializedForm = form.serialize();
//ajax post
$.ajax({
url: "#Url.Action("CompanyEdit", "CV")",
type: "POST",
data: serializedForm
.........
......
Now the serializedForm will be posted to your controller parameter as the ViewModel
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSchool(YourViewModel modal)
{
//find school
var school = repository.FindSchool(modal.Id)
//map value from modal
school.SchoolName = modal.SchoolName;
..........
repository.SaveScool(school);
}

MVC / AJAX send data to controller and load response in same view

I have a page with three form fields (2 textbox, 1 dropdown), a submit button and a 'refresh' link. I want to be able to click the link and pass two form textbox values to a controller action, and get a list of values to populate the dropdown box. I do not want to submit the form at this stage.
At the moment, I have managed to call the controller action from the link click, but I cannot pass the two form field values in for some reason. Also, the return JSON just takes me to a new page instead of populating my dropdown list. Any pointers would be great as I am new to javascript and MVC. My code is below;
Controller
public ActionResult Find(AddressFormViewModel model)
{
...
var temp = new List<OptionModel>();
temp.Add(new OptionModel {Id = item.Id, Value = item.desc});
return Json(temp, JsonRequestBehavior.AllowGet);
}
HTML
#Html.TextBoxFor(x => Model.HouseNameInput, new { id = "HouseNameInput" })
#Html.TextBoxFor(x => Model.PostCodeInput, new { id = "PostCodeInput" })
#Html.ActionLink("Find","Find", "Address", new { houseInput = Model.HouseNameInput, postcodeInput = Model.PostCodeInput }, new { htmlAttributes = new { #class = "Find" } })
#Html.DropDownListFor(x => Model.AddressOption, Enumerable.Empty<System.Web.Mvc.SelectListItem>(), "-- Loading Values --", new {id = "AddressOptions"})
And lastly, my Javascript method which is retrieving the data from the controller action but not populating the dropdown list (it displays the results in a new page). It is also not successfully sending the form values to the controller action.
$(function () {
$('.Find').click(function (evt) {
$.ajax({
type: 'POST',
url: '#Url.Action("Find","AddressFormSurface")',
cache: false,
async: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
houseNameInput: $("#HouseNameInput").value,
postCodeInput: $("#PostCodeInput").value
},
success: function (data) {
if (data.exists) {
var ddl = $('#AddressOptions');
ddl.empty();
data.each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl);
});
}
},
error: function (req) {
}
});
// we make sure to cancel the default action of the link
// because we will be sending an AJAX call
return false;
});
});
You have a number of errors in your script which will cause it to fail.
You specify contentType: "application/json; charset=utf-8", but do
not stringify the data (the option should be removed)
You need to use .val() (not .value) to get the values of the
inputs
The data you receiving does not contain a property named exists so
the if block where you append the options will never be hit
In addition it is unnecessary to generate your link using #Html.ActionLink() (your adding route values based on the initial values of the model). Instead just create it manually
Find
and change the script to
var ddl = $('#AddressOptions'); // cache it
$('#find').click(function () { // change selector
$.ajax({
type: 'GET', // its a GET, not a POST
url: '#Url.Action("Find","AddressFormSurface")', // see side note below
cache: false,
async: true,
dataType: "json",
data: {
houseNameInput: $("#HouseNameInput").val(),
postCodeInput: $("#PostCodeInput").val()
},
success: function (data) {
if (!data) {
// oops
return;
}
ddl.empty();
$.each(data, function(index, item) {
$(document.createElement('option'))
.attr('value', item.Id)
.text(item.Value)
.appendTo(ddl);
// or ddl.append($('<option></option>').text(item.Value).val(item.Id));
});
},
error: function (req) {
....
}
}
});
Side note: Also check the name of the controller. Your Html.ActionLink() suggests its AddressController but your script is calling AddressFormSurfaceController

the required anti-forgery form field __requestverificationtoken is not present Error while ajax call

anti-forgery form field “__RequestVerificationToken” is not present
when using jQuery Ajax and the Html.AntiForgeryToken()
How to make ajax request with anti-forgery token in mvc
AJAX Posting ValidateAntiForgeryToken without Form to MVC Action Method
All the answers above did not help me. I get this error in my request with Jquery Ajax call:
"The required anti-forgery form field "__RequestVerificationToken" is
not present"
If I comment [ValidateAntiForgeryToken] attribute at POST action method it is working fine. I want to know why I am getting this error.
#using (Html.BeginForm("Save", "AddPost", FormMethod.Post, new { id = "CreateForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>GropPost_Table</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Body, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Body, new { id = "Bf" })
#Html.ValidationMessageFor(model => model.Body)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="btnAdd" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Save([Bind(Include = "Body")] GropPost_Table groppost_table)
{
if (ModelState.IsValid)
{
groppost_table.GroupID = 1;
groppost_table.ID = 1;
groppost_table.PostDate = System.DateTime.Now;
db.GropPost_Table.Add(groppost_table);
db.SaveChanges();
return Json(groppost_table);
}
else
{
return Json("we Couldent add your post");
}
}
<script type="text/javascript">
$("#btnAdd").click(function () {
var GropPost_Table = {
"Body": $("#Bf").val()
};
var token = $('#CreateForm input[name=__RequestVerificationToken]').val()
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax( {
type: "POST",
url: "#Url.Action("Save","AddPost")",
data: JSON.stringify(GropPost_Table),
contentType: "application/json;charset=utf-8",
processData: true,
headers:headers,
success: function (dataR) {
$("#Bf").val('');
},
error: function (dataR) {
$("#Bf").val('');
alert(dataR.toString());
}
});
});
</script>
I've alway included the Request Verification Token in the data of the POST and not the headers. I would approach it like this:
First add type="submit" to your input button so it will submit the form when clicked. Then in your javascript:
// Listen for the submit event on the form
$('#CreateForm').on('submit', function(event) {
var $form = $(this);
$.ajax({
// Html.BeginForm puts the url in the
// "action" attribute
url: $form.attr('action'),
// Serializing the form will pick up the verification
// token as well as other input data
data: $form.serialize(),
success: function(dataR) {
$('#Bf').val('');
},
error: function(dataR) {
$('#Bf').val('');
alert(dataR.toString());
}
});
// Preventing the default action will keep the form
// from doing a full POST.
event.preventDefault();
});

Categories

Resources