Return partial view to JSON from controller in MVC

My position

I have a list of subjects (polls) displayed on my home page. When I click the edit button for a specific item, I have a modal popup with details information for editing. When the user clicks Save , I submit the form via ajax. Depending on whether ModelState.IsValid == true, I want to update the modal check information or close the modal version and update the list of items with new information.

This is how I represent the form:

$('#editSurveyForm form').live('submit', function () { var f = $("#saveSurvey").parents("form"); var action = f.attr("action"); var serializedForm = f.serialize(); $.ajax({ type: "POST", url: action, dataType: "html", data: serializedForm, success: function (result) { //TODO - I need an indicator that validation was successful //If Validation Failed reload form with validation errors $('#editSurveyModal').html(result); //If Successful, reload Survey Partial View //$('#surveyBox').html(result); } }); return false; }); 

My questions

The only thing I can do is return JSON from my controller with a flag indicating the state of ModelState.IsValid and the corresponding partial that I should show.

1) How do I do this?

2) Is there a better way?

Update

I found this: http://www.klopfenstein.net/lorenz.aspx/render-partial-view-to-string-in-asp-net-mvc

but most likely I'm wrong about that.

+4
source share
4 answers

One way to skip using JSON is to look for specific elements in the returned HTML. If you use any of the html helpers for validation messages ( Html.ValidationSummary(), Html.ValidationMessageFor() ), they will display elements with specific classes that you can find to determine the result. If not, you can make your own standards.

For example, if you use the Html.ValidationSummary method, it will display a list with the class validation-summary-errors . That way you can set such a variable and then process the response accordingly.

 var isValid = $(response).find(".validation-summary-errors").length == 0; 

So, in your situation:

 success: function (result) { var isValid = $(result).find(".validation-summary-errors").length == 0; //If Successful, reload Survey Partial View if (isValid) { $('#surveyBox').html(result); } //If Validation Failed reload form with validation errors else { $('#editSurveyModal').html(result); } } 
+1
source

You can return a flag that tells you if you have errors or not, and depending on this flag, a different data set. If this is an error, return something like:

 {success: false, errors: ['Name invalid','email invalid']} 

And if this is correct:

 {success: true, Name:'new name',email: 'new email'} 

and your script

 .... $.ajax({ type: "POST", url: action, dataType: "html", data: serializedForm, success: function (result) { if(!result.success) { //Show errors } else { // Update data } } }); ..... 

To show errors, you can have a div in modal popUp, and then for each element in result.errors, add a div inside the error div.

If success is correct, find the item you clicked and update it with the date in your result.

Let me know if you do not know how to do this.

+1
source

Do it as supposed

jQuery Ajax requests can handle success as well as error conditions. Thus, the correct way is to actually return an error message ( not HTTP 200) from the server if there are validation errors. Do not return submissions unless shown. But even in this case, they should be part of an erroneous result displayed using various functions on the client side ( error function of the handler).

Read all the details about this in my blog post . All the code is provided there as well, and everything is explained step by step, so it is easy to understand.

It uses a custom exception class that is generated when there are model state errors and a user error filter , which uses this exception and returns the error to the client side. This makes it very easy to make an Ajax request properly:

 $.ajax({ type: "POST", data: /* your data */, success: function(data, state, xhr) { // do wahetever required }, error: function(xhr, state, err) { // do something about the error ie. inform the user about it } }); 

This is much better than detecting errors in the success state and the absence of an unnecessary branch in it. JQuery is supposed to be used this way, and not just with the success handler.

Sidenite

I apologize for not having seen your question before, because I believe that it will make you happier with the information that it provides.

+1
source

Index method of returning partial view of update. This method will mess up my table like update ajax jquery?

I like to update only the mu table in PartialView . This situation:

  <div class="container container-Top"> <h4>Lista de categorias produtos</h4> <p> <hr /> <br /> @using (Html.BeginForm()) { <div class="form-group"> <div class="col-lg-4"> @Html.TextBox("NomeCategoria", null, new { @class = "form-control" }) </div> @Html.ActionLink("Pesquisar", null, null, new { @class = "btn btn-default", @id = "Pesquisar" }) </div> } <br /> <br /> <br /> <div id="DvDetalheCategoria" class="form-group"> @Html.Partial("_DetalhesCategoria", Model) </div> </div> 

My jquery

  <script type="text/javascript"> $(function () { $("#Pesquisar").click(function () { var $btnPesquisar = $(this); var idCategoria = $("#NomeCategoria").val(); $.ajax({ url: '@Url.Action("_DetalhesCategoria", "VntCategoria")', data: { pName: idCategoria }, type: 'POST', success: function (data) { $("#DvDetalheCategoria").html(data); }, error: function (ex) { alert('Falha ao carregar categorias' + item.Id); } }); }); }); </script> 

My controllers:

  // GET: /VntCategoria/ public ActionResult Index() { return View(db.VntCategoriaProdutos.ToList()); } [HttpPost] public ActionResult _DetalhesCategoria(string pName) { ListaCategorias = new List<VntCategoriaProdutos>(); ListaCategorias = db.VntCategoriaProdutos.ToList().FindAll(f => f.DescricacaoCategoria == pName); return View(ListaCategorias); } 
0
source

Source: https://habr.com/ru/post/1343934/


All Articles