Reputation: 32059
I am pulling some data from an Web API using JQuery Ajax as follows:
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://localhost:43618/api/Products',
dataType: 'json',
success : function(data) {
//some code goes here
}
});
});
</script>
Now, I would like to bind the pulled data to the MVC Model in the following view:
@model IEnumerable<CosumingWebAPIJQuery.Models.Product>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
@if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
</tr>
}
}
</table>
So how can I convert the pulled JSON data into MVC Model Object and bind it to the View to show the data in a list?? Any Help Please??
Upvotes: 1
Views: 1733
Reputation: 218722
You cannot! Your web api is going to return data in JSON format (unless you specify a different accept header). Usually razor code gets executed in the server and html markup will be the output. In your case, you have the json array in client side. you cannot execute razor code there.
One solution (bad solution) is to post the json again to your MVC action method which will then be passed(after converting to your c# class collection) to your partial view and return the view result.
A Better solution is to call an MVC Action method which gets the data and return a partial view result markup. So instead of calling the web api end point, you will call the MVC action method in your web project. If the web api project is part of your MVC web project, you should consider moving the code which returns the data to a common service class method (Which can be called from your web api controller and MVC action method).
Once you get the result from ajax call, which is the HTML markup returned by the partial view, simply udpate the DOM as needed.
Upvotes: 1