Ajax MVC Updating a Dropdown list - c#

I am trying to do a look up with Ajax and a dropdown list, The user enters a postcode in a text box, then clicks search.
From here I want to populate a dropdown list, with the values coming from the database,
The action is in a separate controller :-
public ActionResult Search(string Pcode)
{
return Json(new[] {
new { value = '1', text = "text 1" },
new { value = '2', text = "text 2" },
new { value = '3', text = "text 3" }
});
}
My HTML:
Pcode:- #Html.TextBox("GPPOST")
GP Practice:
#Html.EditorFor(model => model.Patient.GPSurgery)
<br/>
#Html.DropDownListFor(m =>m.Patient.GPSurgery Enumerable.Empty<SelectListItem>(),"-- Select GP --")
GP : <input type="button" id="SearchPcode" value="Search">
And finally the Ajax:
$(function () {
$('#SearchPcode').click(function () {
// get the new value
var value = $(this).val();
// and send it as AJAX request to the action
$.ajax({
url: '/GP_Practices/Search', //'<%= Url.Action("Search", "GP_Practices") %>',
type: 'POST',
data: { pcode: value },
success: function (result) {
// when the AJAX succeeds refresh the dropdown list with
// The JSON values returned from the controller action
var GPNames = $('#Patient.GPSurgery');
GPNames.empty();
$.each(result, function(index, item) {
alert(item.text);
});
$.each(result, function (index, item) {
GPNames.append(
$('<option/>', {
value: item.value,
text: item.text
}));
});
}
});
});
});
When I run the code I do get the Json results back, (which I can see in the alert box).
My 2 problems are:
1)I cannot seem to pass the value from the text box Html.TextBox("GPPOST")
2)The Dropdown list is not refreshing with the new values.

1)I cannot seem to pass the value from the text box Html.TextBox("GPPOST")
That's because your Javascript passes pcode, yet your controller expects Pcode (casing matters).
Also as Ehsan Sajjad mentions, you're not sending the value of the textbox, but this unearths a bigger problem: You're binding two fields to the same model property, you can't do that. You'll have to use a separate field for your dropdown and your search input.
2)The Dropdown list is not refreshing with the new values.
That's because your jQuery selector is incorrect:
var GPNames = $('#Patient_GPSurgery');

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

Saving values of html selects and re-select them on postback

I have five dropdownlists in form of html selects. The first binds at page load using jQuery, and the rest bind when the previous dropdown has been selected. I also have five hidden fields for each dropdown which stores the selected values.
My problem is that when I do a post back, i.e. click the "Search" button, I have to re-populate the dropdowns and select the correct values again by using the ID's in the hidden fields. So far, I've come up with no good way to do this.
In the .aspx page:
<select name="boxFunktionsnedsattning" id="boxFunktionsnedsattning" multiple="multiple </select>
<asp:TextBox ID="HiddenBoxFunktionsnedsattning" runat="server" />
<script type="text/javascript">
function boxFunktionsnedsattningPopulate() {
$.ajax({
type: "POST",
url: "Sok.aspx/getFunktionsnedsattningar",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: LoadBoxFunktionsnedsattning,
failure: function (response) {
alert(response);
}
});
}
//============================================================================================================
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
UpdateBoxEnabledState();
options.multipleSelect("refresh");
}
</script>
Backend code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Funktionsnedsattning[] getFunktionsnedsattningar()
{
GetDataService.IgetDataClient gdc = new IgetDataClient();
return gdc.getFunktionsnedsattningAll();
}
I should add that I'm a beginner when it comes to jQuery, so there is probably something I've overlooked.
IF your using webforms use an onclick function to post back to the server instead of a submit. I think this is the functionality you want because the variables in the inputs of the form will keep its value. Is the search button returning results on the same page or a different one because it will determine the ease in which you can keep varibles during a post back. Good luck!
Got it working with the following solution:
function fillFunktionsnedsattning() {
//stores the value of selected items
var $fn = $('#<%=HiddenBoxFunktionsnedsattning.ClientID%>');
//creates an array of the values in the hidden field
var fnSplit = $fn.val().split(",");
//val() accepts an array which it uses to select items in the list (go figure)
$("#boxFunktionsnedsattning").val(fnSplit);
$("#boxFunktionsnedsattning").multipleSelect("refresh");
//function that triggers the binding of the next dropdown
boxFunktionsnedsattningOnChange();
}
For it to work, this function needs to be called in the function that populates the dropdown. Each dropdown needs it's own fillFunction to be called in the same place, like this, for an example:
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
fillFunktionsnedsattning();
UpdateBoxEnabledState();
options.multipleSelect("refresh");
It's probably possible to simplify this, but this works for me.

Binding a dropdown on the onblur event of a textbox using jquery Ajax

I have a textbox whose value when passed to sp should return a list. I have to bind this list to Dropdown using jQuery Ajax. I have written the sp but my problem is how to bind the dropdown depending on value of textbox in the onblur event of Textbox.
Kindly help. And please excuse for typing errors if any.
i have done similar in my project.
$( "#target" ).blur(function() {
alert( "Handler for .blur() called." );
$.ajax({
url: '../GetRolesAndPriviledgeServlet?filepath='+path+'&type='+type,
type: 'post',
success:function(response){
obj = JSON.parse(response);
$('#DropDownListAssigned').empty();
for (var i=0; i <obj.length ; i++)
{
var oSelField = document.getElementById("DropDownListAssigned");
var oOption = document.createElement("OPTION");
oOption.text = obj[i+1];
oOption.value = obj[i+1];
oSelField.options.add(oOption);
}
},
error:function(){
}
});
});
Try this one
$(document).ready(function () {
$('#txtboxid').focusout(function () {
var yourvalue = $('#textboxid').val();
$.post("/your/url", { Parametername : yourvalue }, function (result) {
$.each(result, function (key, value) {
$('#dropdownid').append($("<option></option>").html(value).val(value));
// Dropdown Binding
});
}, "json");
});
});
Note : Parameter must be same as your controller for example public void data(string nval) means your parameter name also nval

Kendo UI Autocomplete opens twice

I'm using Kendo UI Autocomplete with an ASMX Service which returns a string array like this :
<ArrayOfString>
<string>One string</string>
...
</ArrayOfString>
All works fine except that the items list opens twice. One click close one list and the "second behind" is still open.
When the list's opening we can see the second list opens behind the first.
Any idea ?
JS Code:
<input id="autoCompleteTest" />
<script>
var dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
data: {
startswith: function(){
return $("#autoCompleteTest").data("kendoAutoComplete").value();
}
},
url: "WebService.asmx/GetStrings",
type: "POST",
}
},
schema: {
// specify the the schema is XML
type: "xml",
// the XML element which represents a single data record
data: "/ArrayOfString/string",
// define the model - the object which will represent a single data record
model: {
// configure the fields of the object
fields: {
// the "title" field is mapped to the text of the "title" XML element
value: "text()"
}
}
}
});
$("#autoCompleteTest").kendoAutoComplete({
minLength: 3,
dataValueField : "value",
dataTextField : "value",
dataSource: dataSource
});
</script>
C# Code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String[] GetStrings(string startswith)
{
using (var dataContext = new DataClassesDataContext())
{
var query = from x in dataContext.product where x.shortName.StartsWith(startswith) select x.shortName;
return query.ToArray();
}
}
I've run into a similar issue and posted here
Please confirm that your autocomplete control is not located inside of another control that forces the Kendo control to render a second time.
do you client code when dom is ready for kendo multiselect:
$(document).ready(function () {
..yourcode.});
see: http://docs.telerik.com/kendo-ui/controls/editors/multiselect/overview#accessing-an-existing-multiselect

Categories

Resources