dropdownlistfor selected value list item possible? - asp.net-mvc

I'm currently working in ASP.NET MVC 4 and I'm trying to do something special here.
Here's the code I currently have for my dropdownlist:
#Html.DropDownListFor(m => m.SourceList, new SelectList(Model.SourceList, "Id", "Name", new { id = "SourceList" }))
Now this works, but it's pretty dumb what I'm doing here. In my back-end I query again to get the entire model from the id I just selected.
What I need is not the Id of the selected model, but the entire model. Is there any way of doing this?
My current JQuery callback:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify({ "Id" : selectedStartSourceId, "sourceList" : jsonSourceList }),
success: function (result) {
//Do stuff here
}
});
What I want to be able to do:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: "selectedModel" = modelFromDropDownList,
success: function (result) {
//Do stuff here
}
});

It's probably a bit far-fetched, but you could create a Javascript array representation of your entire list of source objects, and use jQuery and a simple html select ( with the id & name for the options) to retrieve the item from the array.
<script>
var items = [
{
name = "een",
value = "1",
propertyX = "hallo"
},
{
name = "twee",
value = "2",
propertyX = "wereld"
}
];
$("#ddlselect").change(function(e) {
e.preventDefault();
var selectedOptionVal = $(this).val();
var found = null;
foreach (item in items)
{
if (!found && item.value == selectedOptionVal)
found = item;
}
// use found if set
if (found)
{
}
});
</script>
<select id="ddlselect">
<option value="">-- kies --</option>
<option value="1">een</option>
<option value="2">twee</option>
</select>

Related

ajax other parameter is null?

why my other paramter is null. "date" and "ids" is null while my "postedFile" and "amount" has a data. but when i try to removed "postedFile" parameter. the ids and date has a value. and it works fine. but i need the postedfile parameter
My Script
var ids = [];
function add(id, isChecked) {
if (isChecked) {
ids.push(id);
}
else {
var i = ids.indexOf(id);
ids.splice(i, 1);
}
}
function saveSelected() {
//var shipmentId = $('#c-shipment-id').val();
var date = $('#Date').val();
var amount = $('#Amount').val();
//var ImageFile = $('#imageUploadForm').val();
$('#imageUploadForm').on("change", function () {
var formdata = new FormData($('form').get(0));
CallService(formdata);
});
function CallService(postedFile) {
$.ajax({
url: '#Url.Action("index", "payment")',
type: 'POST',
data: { ids: ids, amount: amount, date: date, postedFile: postedFile },
cache: false,
processData: false,
contentType: false,
traditional: false,
dataType:"json",
success: function (data) {
alert("Success");
}
});
}
}
My Controller
public ActionResult Index(int?[] ids, decimal? amount, DateTime? date, HttpPostedFileBase postedFile)
{
return View();
}
As the comments above, I guess you could try to pass all the values with parameters, instead of the variables, like: CallService(formdata, ids, amount, date). It may works.
To answer your secondary question - Fetch all selected IDs in a table with a checkbox column:
Fisrt, add the ID into the checkbox's ID in the view, e.g.:
foreach (var m in Model.Data)
{
row++;
<tr class="#(row % 2 == 0 ? "alter" : "")">
<td class="first">
<input id="chk_#m.ID" type="checkbox" onclick="js_selone(this)" />
</td>
...
Then, Create a JS method getSelVal() to fetch all selected IDs and return an combined string with ,, e.g.: 1,2,3.
$.fn.getSelVal = function () {
for (var e = "", t = $("input[type=checkbox]", this), n = 0; n < t.length; n++) t[n].checked && (e += "," + js_getid(t[n].id));
return e.Trim(",");
}
Finally, you can call the method and pass the ids or ids.toString().split(',') to AJAX request:
ids = $('.table td').getSelVal().toString().split(',');
CallService(formdata, ids, amount, date)
function CallService(postedFile, ids, amount, date) {
$.ajax({
url: '#Url.Action("index", "payment")',
type: 'POST',
data: { ids: ids, amount: amount, date: date, postedFile: postedFile },
cache: false,
processData: false,
contentType: false,
traditional: false,
dataType:"json",
success: function (data) {
alert("Success");
}
});

How to get the value of Dropdown on the specific field using ajax (mvc)

sorry for the bad title I cannot express the proper subject to my problem
since, I'm a newbie in MVC and ajax I have a problem
In view I prepared a dropdown where it list all the shoes name (Shoe Table), now the customer has to select it but the twist it must display the Shoesprice (Shoe Table) once it select a shoe name. the view code is given below
View:
#Html.DropDownListFor(x => x.shoename, new SelectList(Model.ShoesModel,"shoename","shoename"), "Select Shoes Name", new {id="myDrop",#class="form-control" })
I have the script when you select it the item, this particular syntax is working
Script:
$("#myDrop").change(function ()
{
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: $(this).val() },
success: function (data) {
//how can I declare a value to get the and return the price
}
});
}
But, i don't know how to create an ajax syntax (get the price according to shoe name), and set to a controller
thank you for help
Since you want to return single value only, just use data in AJAX success result to show returned price value:
Controller
[HttpPost]
public JsonResult GetShoesPrice(string shoesName)
{
var customerViewPrice = (from c in _SBC.Shoeses // Change the condition here
where c.shoename.Contains(shoesName)
select c.ShoesUnitPrice).FirstOrDefault(); // or SingleOrDefault() for one and only returned value
return Json(customerViewPrice);
}
View (jQuery)
$("#myDrop").change(function () {
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: value },
success: function (data) {
// set input element value which will be posted on form submit with DropDownListFor
$('#price').val(data);
}
});
}
Note that if you want to show list of ShoesUnitPrice from selected shoesName, you need to use $.each() loop to iterate returned array of price value.

Knockout-Kendo dropdownlist Ajax observableArray get selected item name

My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.
The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.

Populating a Webgrid from an Ajax Call

I have a problem with populating a Webgrid from an Ajax call.
I have followed the example as showed in the following thread: mvc3 populating bind webgrid from ajax however, that did not yield any results.
When I run the website, I always get the message: "Error: undefined".
when debugging the code, I am quite sure that the problem lies in the fact that the return PartialView is the problem, as my data object in the ajax success method does not get filled with data.
Here are the examples of my code:
Ajax call:
$.fn.getCardResult = function (leerling, kaart) {
$.ajax({
type: "GET",
url: '#Url.Action("GetResults","Kaarten")',
data: { leerlingID: leerling, cardID: kaart },
cache: false,
success: function (data) {
console.log(data);
if (!data.ok) {
window.alert(' error : ' + data.message);
}
else {
$('#card').html(data);
}
}
});
}
Partial View call:
<div class="card-content" id="card">
#{
if(Model.Kaart != null && Model.Kaart.Count > 0)
{
#Html.Partial("_Kaarten")
}
else
{
#: Er zijn geen kaarten beschikbaar.
}
}
</div>
Partial View:
#model List<ProjectCarrousel.Models.KaartenModel>
#{
var grid = new WebGrid(source: Model,ajaxUpdateContainerId: "card",
defaultSort: "Topicname");
grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column("Topicname", "Topic"),
grid.Column("Taskname", "Taken"),
grid.Column("Taskpoints", "Punten"),
grid.Column("Grades", "Resultaat"),
grid.Column("Date", "Datum"),
grid.Column("Teachercode", "Paraaf Docent")
)
);
}
Controller code:
public ActionResult GetResults(int leerlingID, string cardID)
{
try
{
int Ovnumber = leerlingID;
string CardId = cardID;
List<KaartenModel> kaartlijst = new List<KaartenModel>();
IEnumerable<topic> topics = _db.topic.Include("tasks.studenttotask").Where(i => i.CardID == CardId);
foreach (topic topic in topics)
{
foreach (tasks task in topic.tasks)
{
KaartenModel ka = new KaartenModel();
ka.Topicname = task.topic.Topicname;
ka.Taskname = task.Taskname;
ka.Taskpoints = task.Taskpoints;
ka.Ranks = task.Ranks;
ka.Date = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Date).SingleOrDefault();
ka.Grades = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Grades).SingleOrDefault();
ka.Teachercode = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Teachercode).SingleOrDefault();
kaartlijst.Add(ka);
}
}
KVM.Kaart = kaartlijst;
return PartialView("_Kaarten", KVM.Kaart);
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
If anyone could help it would be greatly appreciated.
UPDATE
After fiddling about a bit I found a solution that worked for me. Below is a snippet of an updated Ajax Call:
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});

railsAutocomplete.select not working when option is selected throgh down arrow

I am using rails3-jquery-autocomplete for autocomplete functionality but when I select through mouse autocomplete works but if I select through keyboard down and arrow and click enter its not working I am having following code. What I am missing
$(".text_field_title").live("focusout",function(){
var name = $(this).attr("name");
var value = $(this).val();
var activity_id = $(this).attr("rel")
var practice_plan_id = $(this).attr('practice_plan_id');
$("#"+activity_id+"_title").bind('railsAutocomplete.select',function(event,data){
var data = [
{
name : name,
value : value
},
{
name : "activity_id",
value : activity_id
},
{
name :"fav_id",
value : data.item.id
}
];
$.ajax({
type: 'POST',
url: 'myurl',
data: data,
dataType: "script"
});
});
});

Resources