Tuesday, 10 September 2013

mapping json returned from controller to strongly typed view

mapping json returned from controller to strongly typed view

Here is my strongly typed view
@using ( Html.BeginForm("Index", "Home",null, FormMethod.Post, new {
id="FormPost" }))
{
@Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
<br />
@Html.TextBoxFor(x => x.LastName) @Html.ValidationMessageFor(x =>
x.LastName)
<br />
@Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
<br />
<input type=submit value="submit" />
<br /><br />
}
This is the view model class:
public class MyViewModel
{
[Required(ErrorMessage="Please enter first name") ]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
}
I post the form back to the Index action method using the script below
ReusableJqueryPost.prototype.CommonPost = function (formId) {
var fid = $("#" + formId);
var validated = $(fid).valid();
if (validated) {
$.ajax({
type: 'POST',
url: $(fid).attr('action'),
data: $(fid).serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.responseText + '-' + error);
},
success: function (response) {
alert('DATA SAVED!');
var resp = response;
}
});
}
};
The Index Action method can now return as ActionResult
return View(objMyViewModel);
or as or JsonResult
return Json(objMyViewModel);
If I was not using a jquery post and was returning data as an ActionResult
then I wouldnt need to do anything on the client side. Asp.net MVC would
take care of binding the values to the appropriate text boxes on account
of the @Html.TextBoxFor(....)
Since I am using a jquery post to post to the action method and returning
data as JsonResult , I want this same flexibility of auto-binding each
element in the json string to the respective Html.TextBoxFor(...)
textboxes instead of having to use jquery to find the textboxes or
selectboxes( if there are any) and then binding the data to it based on
the values received in the json string.
Questions
Is this possible under some feature of asp.net mvc out of the box?
Is the only option available there to use jquery to find the textboxes or
dropdowns or any other input element by name/id and then assign the value
from the json string
Is there any way I can write this assignment once so that I can reuse the
same code without repeating it all over the project for every view? much
like I have one jquery post method here to be used through out the
project.
Thanks

No comments:

Post a Comment