How to load a partialview for an AJAX request?

Asked

Viewed 513 times

1

I can’t carry a partialview in a div !

     <fieldset>
<legend>Contato:</legend>
@Html.Label("Tipo Contato: ")
@Html.DropDownListFor(t => t.CodTipoContato, Model.TipoContatoList, new { id = "tipoContato", name = "tipoContato", onchange = "CarregarPartialView()" })

      <div id="result">
   @if(Model!=null)
   {        
        if (Model.CodTipoContato == 10)
        {
            Html.RenderPartial("_ContatoEmailFields");

        }
        else if(Model.CodTipoContato==0)
        {
            Html.RenderPartial("_EmptyView");

        }

        else
        {
            Html.RenderPartial("_ContatoTelefoneFields");
        }
   }

   <script type="text/javascript">
      function CarregarPartialView(CodTipoContato){        
       var codTipoContato = $("#tipoContato").val();            
        $.ajax(
        {
        type: "GET",
        url: "TipoContato",
        data: "CodTipoContato="+codTipoContato,           
        sucess: function (result) { $('#resultado').html(result)}
         });
        };
     </script>

    public PartialViewResult TipoContato(int CodTipoContato)
    {
        var tcList = ConsultaRepositorio.ObterTipoContato();
        var codTipoContato = CodTipoContato;
        var tipoContatoVM = new SuperViewModel()
        {
            TipoContatoList = Extentions.ObterTipoContatosList(tcList),
            CodTipoContato=codTipoContato
        };
        return PartialView("_ContatoFields",tipoContatoVM);
    }
  • What happens? Some mistake?

  • the partialview is not loaded inside the div!

  • In the callback of your ajax call you are using $('#resultado').html(result) but in your HTML div has the id result. Is that not the problem?

  • not that not ,corrected and continue without carrying the partialview inside the div! does not carry anything!

  • What appears in the tab Network browser developer tools (assuming you are using Firefox or Chrome)?

  • Pow appears my selected partialview!! but pq does not load inside the page??

  • You have to look at the tab Network(or Network) and see what the ajax request returns.

Show 2 more comments

1 answer

0

In your case, don’t use it like that:

Html.RenderPartial("_ContatoEmailFields");

Use like this:

Html.Partial("_ContatoEmailFields");

I explain this in this reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.