Reputation: 195
I'm still getting my feet wet experimenting with MVC3. I haven't found a good resource to get me started. I was wondering if I could consume a webservice that returns a string when a user is done typing in a zip code?
I have consumed a webservice using json but in a ASP.NET web application. I was able to return an Franchise based on the user's entered zip code. I was wondering if I could do the same thing in MVC?
How to convert the following to work in MVC:
// Html code in my Test.aspx page
<input id="txtZipCode" type="text" onchange="javscript:changed(this.value)" />
<div id="Result"></div>
Here my javascript code:
function changed(value) {
$.ajax({
type: "POST",
url: "Test.aspx/GetData",
data: "{'zipcode': '" + value + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
},
error: function () {
$("#Result").text('Failed');
}
});
}
Here's my code behind:
[System.Web.Services.WebMethod]
public static string GetData(string zipcode)
{
srvc.bbcs tmp = new srvc.bbcs (); // consume test webservice
string code = tmp.GetFETerrByZip(zipcode);
return code;
}
Upvotes: 0
Views: 1405
Reputation: 2775
It's very similar, you will have to decorate your Action with the HttpPost attribute so you can accept POST request :
[HttpPost]
public ActionResult GetData(string zipcode)
{
//return DateTime.Now.ToShortDateString();
srvc.BudgetBlindsCommercialSolutions tmp = new srvc.BudgetBlindsCommercialSolutions();
string code = tmp.GetFETerrByZip(zipcode);
return Json(new {code= code});
}
While your jquery call will be :
function changed(value) {
$.ajax({
type: "POST",
url: "YourController/GetData",
data: "{'zipcode': '" + value + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
},
error: function () {
$("#Result").text('Failed');
}
});
}
Upvotes: 1
Reputation: 93424
Yes, and you would do it exactly like you just showed. however, I would not do it on the onchange event, since that means sending a request each time a digit is typed, and that could get confusing. Perhaps on the onblur instead.
Upvotes: 0