Render Ajax received strongly typed data
In mine ASP.NET MVC app
, I have a call Ajax
that reads a record from the server and should show it on the client side. The view file is strongly typed, so I have all the elements on the page.
How can I visualize the received data on the page? Please note that I have to use Ajax to render different data. It's kind of SPA application
, but I really prefer not to use third-party libraries
it unless they have a real edge.
The return of the action method looks like this:
var data = repoH.GetAll().Where(....).FirstOrDefault();
return Json(data);
and the Ajax call:
$(document).ready(function () {
$.ajax({
url: '@Url.Action("action", "controller")',
method: 'post',
success: function (result) {
debugger;
}
});
});
The view looks like this:
<form id="formId">
@Html.HiddenFor(x => x.Id)
<div class="form-group form-inline col-xs-12">
<div class="col-xs-6">
@Html.LabelFor(x => x.fieldA, new { @class = "control-label col-xs-6" })
@Html.EditorFor(x => x.fieldA)
</div>......
</div>
With some buttons and some custom Ajax calls. I have to implement all CRUD operations this way!
Any suggestion is appreciated! Please let me know if something is wrong with me, this app has changed several times and I am really confused!
source to share
I don't really understand if you have the option to do this on the server side, but yes.
At first it ... return Json(data);
is not actually asp.net mvc, because you are not returning a view.
Let's say you have this.
var databaseModel = repoH.GetAll().Where(....).FirstOrDefault();
/* optionally, but best practice var viewModel = map databaseModel to some viewModel */
Then use a method that will turn your viewModel into a string.
// this will be in a RenderingHelper class
public static string RenderViewToString(ControllerContext context, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
ViewDataDictionary viewData = new ViewDataDictionary(model);
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
ViewContext viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
So, you will need to create a part that takes your viewModel (databaseModel) and then save the html render:
string renderedHtml = RenderingHelper.RenderViewToString(this.ControllerContext, "~/Views/MyController/MyPartial", viewModel);
And you can return Json which will contain the rendered html and other data as you want { RenderedHtml = renderedHtml, SomeData = someData }
.
And you get rendered Html in your answer:
success: function (response) {
// test if you have response.RenderedHtml
// and then override your container html with what you rendered on the server $('#your_container_to_render_data_on_the_page').html(response.RenderedHtml);
}
And this is how you create a databaseModel (viewModel) and then render (server side) the corresponding partial view and then return inside json the rendered html on the client side.
I don't see any other approach.
source to share
For example, you have an action like this that returns json
:
[HttpGet]
public ActionResult GetValidConnectionTypes(string code)
{
SelectList validConnectionTypes = GetValidConnectionTypes(code);
return Json(validConnectionTypes, JsonRequestBehavior.AllowGet);
}
And in the view you have a javascript function where you call this action via ajax and get the result like data
:
function loadValidConnectionTypes(code) {
$deferred = $.Deferred();
$.ajax({
url: getValidConnectionTypesUrl,
data: { code: code },
dataType: "json",
type: "GET"
})
.done(function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
var selectItem = $("#ConnectionType");
selectItem.html(items);
$deferred.resolve();
})
.fail(function (r, s, e) {
$deferred.reject();
});
return $deferred.promise();
}
Then, in part, done
just parse data
by creating html (like in example <option></option>
) and add it to page ( selectItem.html(items)
). NTN
source to share