admin管理员组文章数量:1337218
I've scoured through the posts here and haven't found a solution that works...
I am using JQuery autoplete for a dropdown list of employees. I am able to load the list with values but it contains the keys from the dictionary that I am passing and not the values. I want to show both.
Controller code:
public JsonResult GetEmp(string id)
{
if (id.Length > 3)
{
var result = Json(repository.SearchForEmployee(id), JsonRequestBehavior.AllowGet);
return result;
}
return null;
}
Jquery code:
$('.empId').keyup(function () {
var x = $('.empId').val();
var arrayValues = [];
$.ajax({
url: '../../Employee/GetEmployee',
type: "Get",
data: { id : x },
cache: false,
datatype: 'json',
traditional: true,
success: function (result) {
$.each(result, function (item) {
arrayValues.push(item);
})
$(".empId").autoplete({
source: arrayValues
});
},
error: function (err) {
alert('Foo')
}
});
});
JSON result variable in Controller action when debugging:
[0] {[12345, Sharon Moore]}
[1] {[12346, Amy Adams]}
[2] {[12349, Adam Smith]}
Actual contents of JScript array for automplete:
12345, 24563, 84565
Can anyone explain why it is only bringing in the first value(key)? Both key and value are strings. Thanks again in advance...
I've scoured through the posts here and haven't found a solution that works...
I am using JQuery autoplete for a dropdown list of employees. I am able to load the list with values but it contains the keys from the dictionary that I am passing and not the values. I want to show both.
Controller code:
public JsonResult GetEmp(string id)
{
if (id.Length > 3)
{
var result = Json(repository.SearchForEmployee(id), JsonRequestBehavior.AllowGet);
return result;
}
return null;
}
Jquery code:
$('.empId').keyup(function () {
var x = $('.empId').val();
var arrayValues = [];
$.ajax({
url: '../../Employee/GetEmployee',
type: "Get",
data: { id : x },
cache: false,
datatype: 'json',
traditional: true,
success: function (result) {
$.each(result, function (item) {
arrayValues.push(item);
})
$(".empId").autoplete({
source: arrayValues
});
},
error: function (err) {
alert('Foo')
}
});
});
JSON result variable in Controller action when debugging:
[0] {[12345, Sharon Moore]}
[1] {[12346, Amy Adams]}
[2] {[12349, Adam Smith]}
Actual contents of JScript array for automplete:
12345, 24563, 84565
Can anyone explain why it is only bringing in the first value(key)? Both key and value are strings. Thanks again in advance...
Share Improve this question asked Jan 10, 2014 at 17:50 user1171915user1171915 891 gold badge2 silver badges11 bronze badges 4- Do you need quotes around your value strings? – zgood Commented Jan 10, 2014 at 17:54
-
1
What do you see when you
console.log(result)
in yoursuccess
callback? – zgood Commented Jan 10, 2014 at 17:55 - console. log results are:{"1289":"KIRK BELL","1827":"LINDA JONES","1963":"LINDA SMITH"} – user1171915 Commented Jan 10, 2014 at 19:23
- That looks like an object and not an array or array of objects. – zgood Commented Jan 10, 2014 at 19:26
4 Answers
Reset to default 3Since you are returning an object and not an array you could try something like this:
var array_of_objects = [];
for (var key in result) {
var val = result[key];
//Now you have your key and value which you
//can add to a collection that your plugin uses
var obj = {};
obj.label = key;
obj.value = val;
array_of_objects.push(obj);
}
$(".empId").autoplete({
source: array_of_objects
});
Alternatively, you could just return an ArrayList in your C# code (which will be an array of objects/records). Here is some sample code from one of my projects:
[HttpPost]
public ActionResult GetProject(int id) {
string connStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
string sql = "SELECT * FROM [Portfolio] WHERE [id] = @id";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.SelectCommand.Parameters.Add(new SqlParameter("@id", id));
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
da.Dispose();
conn.Close();
return Json(objConv.DataTableToArrayList(dt), JsonRequestBehavior.AllowGet);
}
objConv
is a helper utility I use. Here is the code for the DataTableToArrayList
method I am using in the above code sample:
public ArrayList DataTableToArrayList(DataTable dataTbl) {
ArrayList arrList = new ArrayList();
foreach (DataRow dRow in dataTbl.Rows) {
Hashtable recordHolder = new Hashtable();
foreach (DataColumn column in dataTbl.Columns) {
if (dRow[column] != System.DBNull.Value) {
recordHolder.Add(column.ToString(), dRow[column].ToString());
} else {
recordHolder.Add(column.ToString(), "");
}
}
arrList.Add(recordHolder);
}
return arrList;
}
JQuery UI Autoplete expects a specific data structure to work.
SearchForEmployee must return a list of data in this format:
public class EmployeeAutoplete
{
public string @label { get; set; }
public string @value { get; set; }
}
Or you need to convert in the javascript to that format instead of a list of arrays:
success: function (result) {
$.each(result, function (item) {
arrayValues.push(new { label: item[1], value: item[0] });
});
$(".empId").autoplete({
source: arrayValues
});
},
Autoplete reference: http://api.jqueryui./autoplete/
jQuery UI Autoplete can make the ajax call itself, so I don't really see why you are making the ajax call separately.
$("#txtbox").autoplete({
source: url
});
Regardless of that though, the json from your controller should be returned in the format of [ { label: "Choice1", value: "value1" }, ... ]
if you want to send value and labels back.
http://api.jqueryui./autoplete/#option-source
Here's a piece of code that i am using in a couple of places. I am not using the autoplete feature that you are using but i dont think that is a problem.
Client Side:
$.getJSON('../../Employee/GetEmployee', { id: x }, function (results) {
var yourDropdown = $('#YourDropdown');
var json = JSON.parse(results);
$.each(json, function (index, item) {
yourDropdown.append($('<option/>', {
value: item.Value,
text: item.Text
}));
});
//Implement the autoplete feature.
});
Server Side:
[HttpGet]
public JsonResult GetElements(int id)
{
IEnumerable<SelectListItem> elements;
//Some routine that gets the elements goes here.
var serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(elements), JsonRequestBehavior.AllowGet);
}
I have not tested the code in your particular scenario but it should work since I am using the code snippet in multiple places.
Note: Try using the getJson method instead of $.ajax. It is a shortcut to the ajax implementation you are using. As you can see, the code is less verbose and more readable.
本文标签: javascriptParse keyvalue pair from JSON dictionary result in MVCStack Overflow
版权声明:本文标题:javascript - Parse keyvalue pair from JSON dictionary result in MVC - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743396990a2493738.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论