Reputation: 2449
I have a http controller which is called from a getJSON method. Its working pretty good. But now I want to do the same operation performed in handler in a controller method. I am sending a value through getJSON to handler and it perform with that value.
Here is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
and here is my handler
public void ProcessRequest(HttpContext context)
{
try
{
string strURL = HttpContext.Current.Request.Url.Host.ToLower();
//string ProfileName = context.Request.QueryString["profilename"];
string strProfileName = context.Request["ProfileName"];
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
}
catch
{
}
}
how can I call and pass 'ProfileName' to a controller method ?
Upvotes: 1
Views: 2526
Reputation: 726
You almost have it. Here is an example:
Javascript
function someFunction(e) {
$.post("@Url.Action("MethodName", "ControllerName")", { ParameterName: e.value }, function(data) {
$("#someDiv").html = data;
});
}
C# Controller
[HttpPost]
public ActionResult MethodName(string ParameterName)
{
return "Hello " + ParameterName;
}
If you passed in your name to the JavaScript function "someFunction", the controller would return "Hello [your name]". Help?
Upvotes: 0
Reputation: 1038730
Your code is correct and you should be able to retrieve the ProfileName with the following:
string strProfileName = context.Request["ProfileName"];
And if you wanted to pass it to a controller action simply define this action:
public ActionResult SomeAction(string profileName)
{
var profileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
var request = new ProfileSearchCriteria { Name = profileName };
var profileDetails = profileDataService.GetList(request);
return Json(profileDetails, JsonRequestBehavior.AllowGet);
}
and then invoke your controller action with AJAX:
<scirpt type="text/javascript">
$(document).ready(function () {
var url = '@Url.Action("SomeAction")';
$.getJSON(url, { profileName: 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});
</script>
Upvotes: 3