I have a strongly typed Category View, showing all Category (in a grid) …
Under that grid I have the fields to Add/Edit a new Category details: several textbox and radiobox, like :
– Category Name
– Category Description
– Category Imagem
etc
So, When the user select a Category on Grid, it fills the fields via JQuery Ajax…
$.ajax({
url: '/Category/Get',
type: 'POST',
dataType: 'json',
data: {
idCategory: ...
}
})
.success(function(category,success) {
// Update TextBox fields
$(".ajax").each(function(){
$(this).val(category[$(this).attr("id")]);
});
//Other fields ...
})
My Controller
[HttpPost]
public ActionResult Get(string idCategory)
{
if (ModelState.IsValid)
{
var _category = _categoryRepository.Get(Convert.ToInt16(idCategory));
if (Request.IsAjaxRequest())
return Json(_category);
return RedirectToAction("Index");
}
if (Request.IsAjaxRequest())
return Json(new Category());
return View();
}
It´s working fine !
But I´d like to know if it is the best way to do that… It is possible to do it another way? Maybe using Ajax.BeginForm?
Thanks
Paul
Two possible ways to do this in my view.
1) Return a partial view with the category fields in it each time you change the selected category in the grid. Don’t bother with JSON.
2) If you want to use JSON (which is how I’d probably do it), then use a framework like Knockout.JS to handle the binding. It would look something like this:
Your action could probably be simplified to
Then to save just do whatever you normally do on the server
Edit
If you don’t want to call applyBindings multiple times, you can use templates instead. (I didn’t test this code but it should be very close.)