ASP MVC3 - Make second call to controller once jQuery autocomplete value selected - asp.net-mvc

Below are the jQuery versions that I am referencing in my ASP MVC view
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
Using the autocomplete widget, I would like the form to fill out a separate text box based on the user's selection from the autocomplete list. On this page, the user will begin typing a bank name. Once the user selects which bank they need, another field by the name of Dynamics ID needs to be populated with the appropriate value. Here is the jQuery as it's written right now
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1,
onComplete: function (data) {
$.getJSON('#Url.Action("GetDynamicsId", "AgentTransmission")', data, function (result) {
$('Dynamics').val(result);
})
}
});
});
And here are the two controller methods that are called in the above jQuery
//GET
public JsonResult GetBanks(string term)
{
var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(term))
select c.BankName;
banks = banks.Distinct();
return Json(banks, JsonRequestBehavior.AllowGet);
}
//GET
public JsonResult GetDynamicsId(string term)
{
var dynamics = from c in db.BankListMaster.Where(n => n.BankName.Equals(term))
select c.LinkRepsToDynamicsUniqueId;
dynamics = dynamics.Distinct();
return Json(dynamics, JsonRequestBehavior.AllowGet);
}
Once the user has made a selection from the list, I wanted to be able to send back the ID value to that bank. That serves as the primary key for the BankListMaster table, of which BankName and DynamicsId are both fields. I'm still new to jQuery, however, so I may not be able to do this.
Right now, I've set a breakpoint in the first line of both controller methods. The GetBanks breakpoint fires everytime, however I cannot get the GetDynamicsId to fire at all.
EDIT
Since I'm only selecting the BankName field in the first query, I adjusted the GetDynamicsId method to use the bank name as the parameter.

I do something similar by handling the "select" event. It's not "onComplete" as you had in your example. Your code with this change would be:
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1,
select: function (event, ui) {
$.getJSON('#Url.Action("GetDynamicsId", "AgentTransmission")', { term: ui.item.value }, function (result) {
$('Dynamics').val(result);
})
}
});
});

Related

View content is not displayed correctly after redirected in controller in asp.net mvc

I have a action method in the controller and two views in different language.
public ActionResult Index(Guid id, string languageName)
{
var view = "Welcome_en";
if (languageName == "Spanish")
view = "Welcome_es";
return View(view, model);
}
The default languageName is "English".(In RouteConfig.cs defaults part). So at the beginning, the page is loaded at http://localhost:12091/Some/sssf6bda-9r5e-64d7-9bd2-63c2te616adb.
And I saw the view was Welcome_en.cshtml. in that view I have a dropdown menu for languages to switch active language. I select Spanish then make an ajax call.
$("#Languages").change(function () {
var activeLanguage= $(this).find('option:selected').val();
$.ajax({
url: "/Some/Index",
datatype: "text",
data: { id: '#Model.Guid', languageName: activeLanguage },
type: "POST",
success: function () {
console.log('Success')
}
})
Then I saw the code entered the controller again. The view to be displayed should be Welcome_es.cshtml.
The view Welcome_es.cshtml basically is same as Welcome_en.cshtml. The difference is the content in different language. And I set break points in Welcome_es.cshtml, it did reached. However the final displayed result is still same as Welcome_en.cshtml.
I am not sure why it shows the English view's content, I cleaned the cookies but it is same. Also I set a break point in English page, it didn't go to there when the language was "Spanish".
Your AJAX request is returning your view, but you aren't doing anything with it. If your view is a partial then you can change the success callback in your AJAX call to update the part of the page which the HTML should replace.
$.ajax({
url: "/Some/Index",
datatype: "text",
data: { id: '#Model.Guid', languageName: activeLanguage },
type: "POST",
success: function (html) {
$('.partial').html(html);
}
});
Or if the view is really a full page then don't use AJAX to make the request.
Your current code is making the ajax call, but is not using the response coming from that call.
You should return the partial view result and use that to update the relevant part of your DOM to see the changes. You can do that in the success event of the ajax call
$.ajax({
url: "/Some/Index",
data: { id: '#Model.Guid', languageName: activeLanguage },
type: "POST",
success: function(response) {
$("#someDiv").html(response);
}
});
Assuming you have a div with id someDiv present in your page, the above code will update the inner html of that element with the response coming from your ajax call, which is the html markup generated by the corresponding views (based on the language name you are passing from client side)
I also noticed that you are calling the same action method for your normal page load and the ajax call. In that case, what are you trying to achieve with the ajax call ? You could simply reload the page. No need of ajax.
$(function() {
$("#Languages").change(function() {
var activeLanguage = $(this).val();
window.location.href = "#Url.Action("index","Home")?languageName="
+ activeLanguage +"&id=#Guid.NewGuid()";
});
});
If you are using a page reload, you might want to select the dropdown with the selection from previous page. You may use the Html.DropDownListFor helper with a view model for your page to address this issue.
Add a new property to your view model to store the selected language.
public class YourPageViewModel
{
// Your other existing properties goes here
public string SelectedLanguage { set;get;}
}
Now in your GET action method, you should set the SelectedLanguage property value based on your method parameter.
public ActionResult Index(Guid id, string languageName)
{
var view = "Welcome_en";
if (languageName == "Spanish")
view = "Welcome_es";
var model = new YourPageViewModel();
model.SelectedLanguage = languageName;
return View(view, model);
}
Now in your view, use the DropDownListFor helper method
#model YourPageViewModel
#Html.DropDownListFor(m => m.SelectedLanguage, languages,
new { #class = "form-control" });
Assuming languages is a list of SelectListItem's. Replace it with the collection you have to render the dropdown items.
The helper will render the dropdown with the name and id SelectedLanguage. So make sure you update that in your javasacript as well.
$(function() {
$("#SelectedLanguage").change(function() {
var activeLanguage = $(this).val();
window.location.href = "#Url.Action("index","Home")?languageName="
+ activeLanguage +"&id=#Guid.NewGuid()";
});
});

Kendo Ui dropdownlist with ASP.NET MVC5 onSelect function

I am using Kendo UI Dropdownlist with ASP.NET MVC5.
I want to write a cookie onSelect:
#(Html.Kendo().DropDownList().Name("sss").BindTo(Model).DataTextField("Name").DataValueField("Id")
.Events(e =>
{
e.Select("onSelect");
})
.Deferred()
)
function onSelect(e) {
if ("sss" in window) {
debugger;
var dataItem = this.dataItem(e.item);
alert(dataItem.value);
setCookie(dataItem.value);
}
}
all the functions are reachable and working fine. but I am getting an:
undefined
value instead of Id.
why am I receiving this error? and how can I fix it?
P.S. the Model contain both Id and Name.
Once you get the dataItem, it is an instance of your model used to populate the DropDownList.
So, in order to access the Id field, use the Id field not the value field(which your model does not have).
function onSelect(e) {
if ("sss" in window) {
debugger;
var dataItem = this.dataItem(e.item);
alert(dataItem.Id);
setCookie(dataItem.Id);
}
}

OnClick event on different things like divs, img and so on then use data from those in controller to do something

I been googling for about two hours and couldn't find anything about it.
What does one use(frameowork or maybe it is already uilt up in mvc) to pass data from VIEW to controller.
For example lets say I have a list of products and I wanna delete it without refreshing a page just by clicking on the thing like <div data="23020id" onclick="doSomething()"></div> and so if I would press on that div, something would happen in controller without refreshing the page.
I don't know how to google it or what should I've been aiming for here.
I've seen that many websites does it but I don't really know what they use and how they do it.
Could someone give me any direction?
Let's start with your example.
lets say I have a list of products and I wanna delete it without
refreshing a page just by clicking on the thing like
<div data="23020id" onclick="doSomething()"></div>
Here it simply means you're calling javascript function doSomething() on click. But you can give Id to that div and perform click on that id.
<div id="test"data="23020id"></div>
Now what could be in the this function?
This function called your controller method via an ajax call, which will send Id to the controller which we need to delete.
javascript code:
$('#test').click(function() {
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:id},
success: function(data) {
// update some DOM element with the result returned by the
// server. So supposing that you have some <div id="someContainer">
// that will contain the part of the DOM you want updated:
},
error: function() {
alert("error");
}
});
});
Now when you click on button, that will call your controller method and pass id.
public ActionResult Delete(int Id)
{
// do delete here.
return Json(data);
}
Perform deletion on method and return view, and update it on ajax success.
I suggest you to use Partial View for such things. For more see here: Rendering a Partial View and JSON Data Using AJAX in ASP.NET MVC
you can try with this
you can not return View() from ajax call. you need to retrun Json()
you Action method
public ActionResult Delete(int Id)
{
// delete method call
return Json("success", JsonRequestBehavior.AllowGet);
}
your ajax call
$("#divId").click(function() {
var dataattr = $(this).attr("data"); //use this variable
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:dataattr },
success: function(data) {
refresh your DOM element
},
error: function() {
alert("error");
}
});
});
you could use JQuery for that..
$("#divId").click(function() {
dataattr = $(this).attr("data"); //use this variable
$(this).hide();
});

How to create a dynamic dropdown in mvc

How to create a dropdown whose option values are coming from controller.
controller will be getting it from database table's any column value.
for example if that dropdown is for selecting country, and i have 3 country in my database table's country column, in dropdown it should show the 3 country. And if I add one more value in country table, that also should come in dropdown.
I am new to MVC an this is found bit difficult. I am using mvc5.
NB: since I already one model is refered inside the view, I cant add the model for this dropdown
I have done the same in my own website. This is how I do it:
Firstly, create a action for controller which returns JSON value:
public ActionResult GetCountryNames()
{
List<string> CountryNames = new List<string>();
CountryNames = context.GetCountries(); // your EF context to get countrynames from database
return Json(CountryNames.ToArray());
}
Then in your view add this html mark up:
<select id="countrylist" onchange="DoSomething();"></select>
This is your dropdownlist. It has javascript function declared in "onchange" event, if you want to do something when value changes.
Lastly, you need to add your javascript function, which does ajax call to your controller action, gets values and set it to your dropdownlist:
function GetCountryList() {
var serviceURL = '/Home/GetCountryNames';
$.ajax({
type: "post",
dataType: "json",
url: serviceURL,
success: successFunc,
async: false,
error: errorFunc
});
function successFunc(data, status) {
var countrylist = $('#countrylist');
countrylist.empty();
for (var i = 0; i < data.length; i++) {
var $option = $("<option>", { id: "option" + i });
$option.append(data[i]);
countrylist.append($option);
}
}
function errorFunc(data, status) {
alert('error');
}
}
And when your document is ready, run function GetCountryList().
Probably easiest is to do it with jQuery. Like this:
<script type="text/javascript">
$(document).ready(function () {
GetCountryList();
});
</script>

How to Prevent Page refresh on select change for dropdownlist in MVC

I have a dropdownlist in my razor view MVC like
#Html.DropDownListFor(n => n.EMP_ID, (SelectList)ViewBag.EmployeeList, new { #id = "ddlemployee" },"---choose an Employee Name--").
I have applied select change event to drop-down using jquery, when select Employee name getting Employee names and realted data, but problem is when i select a value in drop-down, dropdownlist setting again set to default first value,
It is not sticking to particular selected value, in terms of Asp.net terminology, how to prevent postback to dropdownlist?
//Redirected to Controller
<script>
$(document).ready(function () {
$("#ddlemployee").change(function () {
location.href ='#Url.Action("GetEmployeeDetails", "Employer")'
});
});
</script>
//Action Method in Employer Controller
public ActionResult GetEmployeeDetails(Timesheetmodel model)
{
try
{
ViewBag.EmployeeList = objts.getEmployeeNames();
var emps = from n in db.TIMESHEETs
where n.RES_ID == model.EMP_ID
select n;
int count = emps.Count();
foreach (TIMESHEET ts in emps)
{
model.PROJ_ID = ts.PROJ_ID;
model.SUN_HRS = ts.SUN_HRS;
model.MON_HRS = ts.MON_HRS;
model.TUE_HRS = ts.TUE_HRS;
model.WED_HRS = ts.WED_HRS;
model.THU_HRS = ts.THU_HRS;
model.FRI_HRS = ts.FRI_HRS;
model.SAT_HRS = ts.SAT_HRS;
}
}
catch (Exception ex)
{
throw ex;
}
return View("Timesheet", model);
}
ASP.Net Webforms achieve StateFullness by using Some thing called ViewState
It is implemented as hidden fields in the page to hold data between requests.
This way , asp.net webforms achieves post back mechanism and was able to hold values in bewteen the requests.
Since Http is a stateless protocol , which means it has no relation between requests.
View State is absent in ASP.Net MVC.
So, you have to stop postback by partially posting back . Which means that you need to send an asynchronous request with out refreshing whole page.
It is possible by using AJAX. You can either use
MVC Ajax or Jquery Ajax.
By using AJax, we can eliminate the post back and then do the partial post back.
Solution:
$("#dropdownid").change(function(event e)
{
//Make your ajax request here..
});
Hope this helps
Updated:
$("#dropdownid").change(function () {
$.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
url: /*Your URL*/,
success: function (data) {
//do your callback operation
}
});
});
Got it.
Passing Empid as querystring from jquery like:
<script>
$(document).ready(function () {
$("#ddlemployee").change(function () {
debugger;
var empid = $("#ddlemployee").val();
location.href = '#Url.Action("GetEmployeeDetails", "Employer")?empid=' + empid ;
});
});
</script>
and assign "empid " to model "Empid" in Action method before foreach loop like
model.EMP_ID = empid;//in Controller Action Method before foreachloop of my code
// and this model.EMP_ID binded to dropdownlist.
this EMP_ID passes same id to dropdownlist which was selected. Thats it.

Resources