How to read the result of ajax with c #?

2

I have this code that makes me a query an action of my controller, which returns a list in JSON

function CargPregRegist(valor) {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("CargPregTipo")',
        data: "tipo=" + valor,
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        success: function (data) {
            if (data) {

            }
        }
    });
}

What I have thought to do is capture the result of data but with c # so I can make a query with razor, someone knows how I can read that data with c # ????? I'm working with asp.net mvc 5

part of what I have planned to do is this

@foreach (var m in t)
                    {
                        if (Model.Sto_TipoAlertas_Preguntas.lol(m.CodigoInterno1).TipoAlerta1 > 0)
                        {
                            <option value='@m.CodigoInterno1' selected>@m.DetallePregunta1</option>
                        }
                        else
                        {
                            <option value='@m.CodigoInterno1'>@m.DetallePregunta1</option>
                        }
                    }

What this part of the code has to do, select the ones that do comply with and show in a separate list now where is the 0 is what I'm going to replace by the way I get the result of ajax

    
asked by Jhonny Luis 24.10.2017 в 20:16
source

2 answers

0

You add the code similar to this:

if (data){
  for(i in data) {
     $("#id_select").append("<option value=" + data[i].CodigoInterno1 +
       ">" + data[i].DetallePregunta1 + "</option>");
   }
}

in the view you create your select:

<select id="id_select">
   <option value="0">[--Seleccione un Nombre--]</option>
</select>
    
answered by 24.10.2017 в 23:44
0

It could help you return the result in a string with html format and assign it to the con jquery. From the C # method you can do the validation that you need and in this way you only send the content that you need to show to your view to assign it to the

I'll give you an example that I hope will be of your help

C # code where the answer is formatted:

var lstHtml= new StringBuilder();
                lstHtml.Append("<option selected='selected' value='-1'>-- Seleccionar --</option>");

                lstHtml.Append(string.Join(string.Empty, lista.Select(x =>
                string.Format("<option value='{0}'>{1}</option>",
                x.Id,
                x.Descripcion
                )).ToList()));
                comboHtml = lstHtml.ToString();

Ajax answer code:

if (data) {
       $("#id_select").html(data.comboHtml);
        }
    
answered by 25.10.2017 в 09:33