ASP.NET MVC 4.5 OnBlur event TextBox - c#

I have a C# ASP.net MVC 4.5 solution. I want to create a form with automated address validation.
If you enter a zipcode and housenumber the streetname en city is looked up using an external REST API.
After filling in the housenumber there must be a call to a function in a controller (using AJAX) to look up the address, update the model data and show the result in the form. I can't figure out how to do this.
I was thinking about doing a form post (using AJAX) fired when the onBlur from the housenumber is called. But is this the best way ? Is it really the best way is posting back the whole form ?
Example so far:
<div class="col-md-7">
#Html.TextBoxFor(model => model.HouseNumber, new { #class = "form-control", #placeholder = "HouseNumber" })
#Html.ValidationMessageFor(model => model.HouseNumber, null, new { #class = "text-danger" })
</div>
When the TextBox HouseNumber lost focus I want to call the function 'ValidateAddress' in my controller 'AddressBook'. The function will lookup the streetname and city and will fill the model.Streetname and model.City fields.

Well, you could change your controller action to return the model as JSON:
public ActionResult ValidateAddress(YourModel model){
// Do your validation
return Json(model);
}
and then add an AJAX call to this action and fill your form in the callback:
$( "#HouseNumber" ).blur( function() {
$.ajax({
url: "/yourActionUrl",
type: "POST",
data: $("#yourForm").serialize(),
dataType: "json"
}).done(function( model ) {
$("#Streetname").val(model.Streetname);
$("#City").val(model.City);
});
});

You can have blur event on HouseNumber textbox
try this
#Html.TextBoxFor(model => model.HouseNumber, new { #class = "form-control", #placeholder = "HouseNumber" onblur = "alert('call some javascript function')"})
or
better use jquery function
updated:
$("#HouseNumber").blur(function () {
$.get("ControllerName/ActionMethod",{parameterName:value},function(data){
// extract values from data object and assign ut to your controls
});
});

make your get Mathod on controller with same model parameter
public ActionResult Login(LoginData model)
{
if (model == null)
{
model = new LoginData();
}
return View(model);
}
after filling hoseno Call your function if you want you can use ajax and redirect to your getmethod and pass your model
for validation use script validation so that you can remove or add according to your conditions.

Related

Sending a SelectList Selection to a Create View from a Layout Modal MVC 5

I have a small view inside of an HTML.Action that lives inside my _Layout. I am trying to send the ProjectId of the selected project to the Create Ticket View. My modal view looks like this.
Here is the controller method for the modal view:
[AllowAnonymous] // Change this to only submitters
public ActionResult NavRoleItems()
{
ViewBag.ProjectId = new SelectList(db.Projects, "Id", "Name");
return View();
}
Modal View
#using (Html.BeginForm("Create", "Tickets", FormMethod.Get))
{
#Html.AntiForgeryToken()
<div class="modal-body">
#Html.DropDownListFor(p => p.ProjectId, null, new { #class = "form-control"})
</div>
<div class="modal-footer">
<input type="submit" value="Add Issue" />
</div>
}
And I want to send any way I can really, but Ideally I want to send it as the projId variable below. Im in school and this is the first time I have played with Formmethod.Get.
Controller View
public ActionResult Create(string projId)
{
TicketCreateViewModel model = new TicketCreateViewModel();
var userId = User.Identity.GetUserId();
var user = db.Users.Find(userId);
model.OwnerUserId = userId;
model.OwnerUser = user;
model.ProjectId = projId;
model.AssignedToUserId = new SelectList(db.Users, "Id", "FirstName");
ViewBag.TicketPriorityId = new SelectList(db.TicketPriorities, "Id", "Name");
ViewBag.TicketStatusId = new SelectList(db.TicketStatuses, "Id", "Name");
ViewBag.TicketTypeId = new SelectList(db.TicketTypes, "Id", "Name");
return View();
}
Every way that I have tried it, html hidden and as a param in the begin form, doesn't work because it sees the #Model.ProjectId as null when it loads. As it should bc it is null. But how can I tell it to send it to the Create Tickets controller after the user selects and hits submit?
First Change This in your view
#Html.DropDownListFor(model => model.ProjectId, new SelectList(ViewBag.ProjectId , "Value", "Text"), "...", htmlAttributes: new { #class = "form-control" })
Change your controller variable name by ProjectId
It might Work fine
Another Way
You can add onclick in your button
function submitForm()
{
$.ajax(
{
url: 'Url',
type: "GET",
contentType: "application/json",
data: JSON.stringify({projId: $('ProjectId').val()}),
success: function(objStatus) {},
error: function(xhr, status, error)
{
if(status === "timeout")
{
alert(msg_timeout);
}
else
{
alert(msg_error);
}
},
});
}
why you set null the feeder argument of dropDownListFor ?
set with ViewBag.ProjectId content instead of null
Or
you can fill the viewbag with projects data and in view
do like this :
Controller
[AllowAnonymous]
public ActionResult NavRoleItems()
{
ViewBag.Projects = db.Projects;
return View();
}
View
add a model top of the page that it has ProjectId property
#Html.DropDownListFor(x => x.ProjectId, new SelectList(ViewBag.Projects, "Id", "Name"))
change Create action argument to type that insert top of the view

mvc Html.BeginForm different URL schema

I'm creating a form for a DropDown like this:
#{
Html.BeginForm("View", "Stations", FormMethod.Get);
}
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
#{
Html.EndForm();
}
If I choose a value from my dropdown I get redirected to the correct controller but the URL is not as I would like to have it:
/Stations/View?id=f2cecc62-7c8c-498d-b6b6-60d48a862c1c
What I want is:
/Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c
So how do I get the id= querystring parameter replaced by the more simple URL Scheme I want?
A form with FormMethod.Get will always post back the values of its form controls as query string values. A browser cannot generate a url based on your route configurations because they are server side code.
If you really wanted to generate /Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c, then you could use javascript/jquery to build your own url and redirect
#using (Html.BeginForm("View", "Stations", FormMethod.Get))
{
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"))
}
var baseUrl = '#Url.Action("View", "Stations")';
$('#id').change(function() {
location.href = baseUrl + '/' $(this).val();
});
Side note: Submitting on the .change() event is not expected behavior and is confusing to a user. Recommend you add a button to let the user make their selection, check it and then submit the form (handle the button's .click() event rather that the dropdownlist's .change() event)
Remove "id"
from
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })

Return a value from a model to the controller

I have an application where if the joint owner == yes it should show a partialview. My Model.cs is
[Display(Name = "Joint Owner")]
public string JointOwner { get; set; }
and my view is
<div class="form-group">
#Html.LabelFor(m => m.JointOwner, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<label>#Html.RadioButtonFor(m => m.JointOwner, new { #class = "form-control", value="Yes"}) Yes</label>
<label>#Html.RadioButtonFor(m => m.JointOwner, new { #class = "form-control", value = "No" }) No</label>
#Html.ValidationMessageFor(m => m.JointOwner)
</div>
</div>
I need it to return a partialview when the value of yes is selected. How would I handle this in the model? or would it be more advised to use javascript/jquery?
public ActionResult PrimaryApplicant(PrimaryApplicantViewModel model)
{
// Make sure session didn't get eaten.
var loanType = "";
if (Session["LoanType"] != null)
{
loanType = Session["LoanType"].ToString();
}
// Here we decide which view to show next. in the frotn end you may need to handle what to change labels to in the wizard maybe via JQ/JS
if (loanType == "Auto Refinance")
{
return PartialView("AutoRefinance");
}
else if (loanType == "Auto Purchase")
{
return PartialView("AutoPurchase");
}
else
{
// You'd want to actually handle it if somehow you got a bad value, I just did it so VS didn't whine.
return PartialView("PrimaryApplicantPartial");
}
}
It would b better if you use jQuery if you want an instant result rather than handling it on the back-end/models. If your not fond of the partial view, just make it a hidden div and if Joint Owner Says yes, just make it visible. You can use jQuery hide and show.
It is more preferable to use jquery, and you can use like that:
first create the container for partial view in your view i.e.
<div class="table-rec-container"></div>
then create a function inside the document.ready() like this:
function Partialview() {
var chkradio = $('#JointOwner').val();
if(chkradio ==true)
{
jQuery.ajax({
url: 'url of partial view',
type: "GET",
success: function (data) {
$('.table-rec-container').html("");
$('.table-rec-container').html(data);
}
});
}
}

Call post function when dropdown selected change in mvc4

I was Bind one dropdown with some values and call my post action when dropdown selected changed .for look like
#Html.DropDownListFor(m => m.DistrictId, Model.DistrictList, "Select", new
{
disableValidation = "true",
onchange = #"
var form = document.forms[0];
form.action='Index';
form.submit();"
})
This is working fine for call my controller post action . But I can't get dropdown selected value in my model DistrictId property .
For my controller function is look like below
[HttpPost]
public ActionResult Index(HomeModel homeModel)
{
AdminController adminController = new AdminController();
Guid userId = new Guid();
homeModel.ComplianceModelList = complianceRepository.LoadComplianceModel(userId, homeModel.DistrictId);
LoadDistrict(homeModel);
return View(homeModel);
}
I want to the dropdown selected DistrictId in my homeModel.DistrictId property .
How to do ?
Change your Markup like this
#Html.DropDownListFor(m => m.DistrictId, Model.DistrictList, "Select")
and have some javascript to handle your change event so that it will serialize your form and send it to your action method using ajax.
$(function(){
$("#DistrictId").change(function(e){
var _this=$(this);
$.post("#Url.Action("Index","Home")",_this.closest("form").serialize(),
function(response){
// do something with response.
});
});
});
Assuming you have jQuery library loaded to your page.
Now I got the solution
Below code was working good .
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h2 class="gridTitle">
Compliance</h2>
if (User.Identity.IsAuthenticated && User.IsInRole("SuperAdmin"))
{
<div class="complianceSubDiv">
<div class="complianceRightDiv">
#Html.LabelFor(model => Model.DistrictId)
#Html.DropDownListFor(m => m.DistrictId, Model.DistrictList, "Select", new
{
disableValidation = "true",
onchange = #"
form.submit();"
})</div>
</div>
}
}

Autocomplete field in a form ? []

I work with c# MVC3 & razor, Entity Framework and Linq.
I have a form, with two field, the first one Client ID and the second one Store Name.
I would like, when the user enter the ID, then my StoreName field fill automatically... The data would come from a database where this two data are stored.
You could use AJAX. So setup a controller action taking a client id as parameter and that would query your database and return the corresponding store name as JSON result. Then subscribe to the .blur event of the text input containing the store id and send an AJAX call to the controller action to fill the second input field.
Yeah, I know, meaningless jibber-jabber, gimme the codez.
Here:
public ActionResult GetStoreName(int clientId)
{
// of course thath's just an example here. I have strictly no idea
// what database access technology you are using, how your models look like
// and so on. Obviously you will have to adapt this query to your data model.
var client = db.Clients.FirstOrDefault(x => x.Id == clientId);
if (client == null)
{
return HttpNotFound();
}
return Json(new { storeName = client.Store.Name }, JsonRequestBehavior.AllowGet);
}
Now assuming the following view:
<div>
#Html.LabelFor(x => x.ClientId)
#Html.TextBoxFor(x => x.ClientId, new { id = "clientId", data-url = Url.Action("GetStoreName") })
</div>
<div>
#Html.LabelFor(x => x.Store.Name)
#Html.TextBoxFor(x => x.Store.Name, new { id = "storeName" })
</div>
in a separate javascript file you could subscribe to the .blur event of the first textbox, and trigger the AJAX request to the controller sending it the client id that was entered by the user. In the success callback you would update the second textfield with the result of the AJAX call:
$(function() {
$('#clientId').blur(function() {
var clientId = $(this).val();
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
data: { clientId: clientId },
success: function(result) {
$('#storeName').val(result.storeName);
}
});
});
});

Categories

Resources