Autocomplete field in a form ? [] - c#

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);
}
});
});
});

Related

MVC - How to Return Multiple Attributes while using a dropdownlist

So basically you can refer to this in order to have a clearly view on what I want to achieve in my website.
The corresponding input such as Price and Item will get the information of the selected Gift Basket from database and appended inside the input tag so that the user can adjust the price or adding some item the the customer wanted.
Before Selecting a Gift Basket.
After Selecting a Gift Basket.
Is there any reference or example I can refer to in order to achieve this funtion
1- in the dropdown list add htmlAttributes onchange
#Html.DropDownListFor(model => model.GiftBasket, null, "--Select Gift Basket--", htmlAttributes: new { #class = "form-control ", onchange = "getprice()" }
2- insert below script to get price and item from controller
<script>
//get price & Item
function getprice() {
var strSelected1 = "";
$("#GiftBasket option:selected").each(function () {
strSelected1 += $(this)[0].value;
});
$.ajax({
url: "/your-Controller/getGiftBasket?GiftBasketID=" + strSelected1,
type: "post",
cache: false,
success: function (result) {
document.getElementById('price').value = result[0].price;
document.getElementById('item').value = result[0].item;
},
error: function () {
alert("something wrong");
}
});
};
</script>
3- insert below JsonResult to the controller
[HttpPost]
public JsonResult getGiftBasket(int? GiftBasketID)
{
var GiftBasketitem = db.Giftitem.Where(e => e.GiftBasketID== GiftBasketID).Select(e => new { e.item,e.price });
return Json(GiftBasket, JsonRequestBehavior.AllowGet);
}

How to pass data from a controller to view during a JQuery AJAX call in MVC?

In my view, I have an AJAX call which sends an id parameter to my controller. This bit works fine. In my controller, I plan to query the database with that id, pull out associated data and want to send this back to the AJAX call/view. This is the bit I am struggling with, as I am new to AJAX calls.
var chosenSchoolID = $("#SelectedSchoolId").val();
$.ajax({
url: "/Home/GetSchoolDetailsAJAX",
type: "POST",
data: {
schoolID: chosenSchoolID
},
dataType: "text",
success: function(data) {
if (data == "success") {
}
},
error: function(data) {
if (data == "failed")
alert("An error has occured!");
}
});
The above is my AJAX call, and this does hit my controller method. However in my controller, I want to now send back other string data and I am unsure on how to do this (just placeholder code currently)
[HttpPost]
public ActionResult GetSchoolDetailsAjax(string schoolID)
{
// query database using schoolID
// now we have other data such as:
string SchoolName = "";
string SchoolAddress = "";
string SchoolCity = "";
return null;
}
Must I declare variables in my Jquery and pass into the data parameter of the AJAX call in order for the values to be passed?
Many thanks in advance
The simplest way to do this is to return the entities retrieved from your database using return Json() from your controller.
Note that when retrieving data then a GET request should be made, not a POST. In addition the default MVC configuration should have the routes setup to allow you to provide the id of the required resource in the URL. As such, try this:
$.ajax({
url: "/Home/GetSchoolDetailsAJAX/" + $("#SelectedSchoolId").val(),
type: "get",
success: function(school) {
console.log(school);
},
error: function() {
alert("An error has occured!");
}
});
[HttpGet]
public ActionResult GetSchoolDetailsAjax(string id) {
var school = _yourDatabaseContext.Schools.Single(s => s.Id == id); // assuming EF
return Json(school);
}
If you'd like to test this without the database integration, amend the following line:
var school = new {
Id = id,
Name = "Hogwarts",
Address = "Street, City, Country"
};

executing mvc controller using either Jquery or Ajax call

I am trying to mimic an mvc ActionLink. I want the whole row to be clickable. when the actionlink is clicked, it calls the connected controller and executes the code within. I want my Jquery/ajax call to do the same.
I've tried multiple ways of doing this with no luck. I'm currently at a point where the row is clickable and the Jquery sees that, however the ajax call does not execute. Or, if it does, the controller does not execute correctly
Here is the Jquery code that catches the click.
$(document).ready(function () {
$('#policyTable').on('click', '.clickable-row', function (event) {
$(this).addClass('primary').siblings().removeClass('primary');
var Id = $(this).closest('tr').children('td:first').text();
var url = "/Home/ReviewPolicy";
var uc = $(this).closest('tr').children('td:first').text();
alert("Does the click work? " + Id);
$.ajax({
type: "POST",
url: "/Home/ReviewPolicy",
dataType: 'text',
data: { Id: Id }
});
})
})
Here is the controller it is calling:
[HttpPost]
public ActionResult ReviewPolicy(string Id)
{
//Declare policyVM for individual policy
PolicyRenewalListVM model;
int val = Convert.ToInt32(Id);
using (Db db = new Db())
{
//Get the row
PolicyRenewalListDTO dto = db.RenewalPolicies.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found.");
}
//initialize the PolicyRenewalListVM
model = new PolicyRenewalListVM(dto);
}
//return view with model
return View(model);
}
When the actionlink itself is clicked (It's not here in the code as I didn't see it being necessary for this problem) it fires and everything works as it should, but the jquery call, sending the very same value (Id) does not.

How to get selected index changed value in controller mvc c#

I am getting value in a dropdown list and I wanted to get the selected value in controller when user select any value from the dropdown list. My view is -
#using (Html.BeginForm("ApReport", "Sales", FormMethod.Post))
{
#Html.DropDownList("Ddl", null, "All", new { #class = "control-label"})
#Html.Hidden("rddl")
}
controller -
[HttpPost]
public ActionResult ApReport(ApReport Ddl)
{
string Ddlvalue = string.Empty;
if (Request.Form["rddl"] != null)
{
Ddlvalue = Request.Form["rddl"].ToString();
}
}
but I am not getting any value. Also, I donot want to use any submit button.
Thanks in advance
The use of Ajax allows you as the developer to update the main view without reloading the entire page, as well as send data to the server in the background.
This is how I would have accomplished this task.
Firstly, I would have created an action in my controller which returns a JsonResult. This will return a JSON object to your calling jquery code, that you can use to get values back into your views. Here is an example of the action method.
[HttpGet]
public JsonResult YourActionName(string selectedValue) //Assuming key in your dropdown is string
{
var result = DoYourCalculation(selectedValue);
return Json(new { myResult = result }, JsonRequestBehavior.AllowGet);
}
Now, you need to add your jquery code. I would recommend you place this in a seperate javascript file referenced by your view.
Here is the JQuery code, with the ajax call to the Action in your controller. The Ajax call to the server is initiated by the 'change' event of your DropDown, handled in JQuery, as can be seen below.
$(function () {
$(document)
.on('change', '#Ddl', function(){
var valueofDropDown = $(this).val();
var url = '/YourControllerName/YourActionName';
var dataToSend = { selectedValue: valueofDropDown }
$.ajax({
url: url,
data: dataToSend,
type: 'GET',
success: function (dataReceived) {
//update control on View
var receivedValue = dataReceived.myResult ;
$('YourControlIDToUpdate').val(receivedValue);
}
})
});
};

ASP.NET MVC 4.5 OnBlur event TextBox

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.

Categories

Resources