I have a list defined in my controller. Now i want to get user input ,check if it exists in list in controller and then get all it related value.
Controller
private List<M> Ma()
{
List<M> md = new List<M>()
{
new M{ R="a", A=300, T= 1, P=40, N=1200},
new M{ R="Bl", A=100, T= 150, P=400, N=1200},
};
return mapData;
}
Your controller should look like this:
public ActionResult DashData(double a)
{
return Json(md.FirstOrDefault(map=>map.a == a));
}
While md is the List you defined first
then ur AJAX call should be like this:
$.ajax({
url: "../Home/DashData",
type: "POST",
data: {'a':a},
success: function (data) {
qv.val(data.a);
}
});
Firstly, change the ajax call to
var a = $('input').val();
var qv = $('.act');
var tv = $('.tot'); // you don't seem to use this
$.ajax({
url: '@Url.Action("DashData", "Home")', // never hard code the url!
type: "POST",
data: { a: a }, // change this
success: function (data) {
// access the properties of the object
var A = data.A; // returns 300
var T = data.T; // returns 1
var P = data.P; // returns 40
var N = data.N; // returns 200
}
});
Side notes:
var a = $('input').val();
will always return the value of the first <input>
in the view, so suggest you use the id
attribute ($('#myInput').val();
)$.post('Url.Action("DashData", "Home"), {a: a }, function(data) { ... })
Next modify the controller method to accept the parameter your passing and return the matching Map
object
public ActionResult DashData(string a)
{
// Get the first matching MapModel
MapModel map = MapData().FirstOrDefault(m => m.R == a);
return Json(map);
}