Modifying from MVC to WebAPI
I have to make a private personal site to work with Android / IPhone /Windows Phone natively. So I have to open the data from the site.
But what is better then http://en.wikipedia.org/wiki/Eating_your_own_dog_food ? So I decide to do modifications for this
The site was a simple listing of steps to solve a dangerous situation –see the below image:
The code was realize with a ViewModel and some ajax call( cascading drop downs) .
The ViewModel was this
public class ChooseDangerSituation
{
public List<KVD> Danger;
public List<KVD> Situation;
public List<Tuple<int, int>> DangerSituation;
So I list here the steps:
1. Returning the same ViewModel class from the WebAPI:
public class SurvivingController : ApiController
{
public ChooseDangerSituation DangerSituations()
2. Modifying view controls and loading from javascript:
In my example instead of DropDownList :
var danger = Model.Danger.Select(item => new SelectListItem() { Text = item.Value, Value = item.Key.ToString() }).ToArray();
@Html.DropDownList("idDanger",danger, "Danger")
I had to modify into select :
<select id="idDanger" name="idDanger">
<option value="">Danger</option>
</select>
3. Modify all JsonResult to HttpResponseMessage
This
return Json(new { ok = true, data = q });
will become this
return Request.CreateResponse(HttpStatusCode.OK, new { ok = true, data = q });
Side note:
For a real application you should generate unobtrusive validation. Also, you may want to create Validationmessages. Also WebApi let’s you define routes more easily: [Route("GetSteps/{idDanger}/{idSituation}")]
That it will be all.
Leave a Reply