How to pass parameters of the view to the Controller in ASP.NET MVC with httpPost

1

Hello, what I need is to select a user's id and the date and I must upload the coordinates of that date in a Google Maps.

Model

public class RutaRastreoModel
    {
        public List<Error> Error { get; set; }
        public users[] usersList { get; set; }
        public RutaRastreo[] rutaRastreosList { get; set; }   
    }

    public class VerRutaModel {
        public List<Error> Error { get; set; }
        public RutaRastreo[] rutaRastreosList { get; set; }
        public int iduser { get; set; }
        public string Fecha { get; set; }
        public double Longitud { get; set; }
        public double Latitud { get; set; }
    }

Controllers

 public ActionResult Localizacion()
 {
 if (Session["LoginInfo"] == null)
 {
 /* redireccionamiento para cuando se termine la session y evitar que el login aparesca en el contenido */
 return Content("<script>window.location = '" + Url.Action("Login", "Home") + "';</script>");
 }
   /* Extraemos el contenido de la sesion */
 RutaRastreoModel model = new RutaRastreoModel();
 InfoSession DatosSesion = (InfoSession)Session["LoginInfo"];
 model.Error = new List<Error>();
  try
 {  
 Users_GetResponse userRespuesta = null;
 Users_GetRequest userDatos = new Users_GetRequest()
 {
  Codigo_Sesion = DatosSesion.Codigo_Sesion,
  };
 if (SBClient.dbusers_Get(userDatos, out userRespuesta))
  {
   model.UsersList = userRespuesta.List_Users;
  }
  else
  {
   model.Error.Add(userRespuesta.Error);
  }
  return View(model);
  }
  catch (Exception e)
 {
  model.Error.Add(new Error() { Message = e.Message, Code = "CATDETCRED" });
 return View(model);
}
}

[HttpPost]
public ActionResult VerRuta(int user, string fecha)
{
 
 VerRutaModel model = new VerRutaModel();
 model.Error = new List<Error>();
         
try
{
Rastreo_Ruta_GetResponse rutaRespuesta = null;
Rastreo_Ruta_GetRequest rutaDatos = new Rastreo_Ruta_GetRequest();
{
rutaDatos.Codigo_Sesion = DatosSesion.Codigo_Sesion;
user = rutaDatos.user;
fecha= rutaDatos.Fecha;
};

if (SBClient.dbRastreo_Ruta_Get(rutaDatos, out rutaRespuesta))
{
model.rutaRastreosList = rutaRespuesta.List_Ruta_Rastreo_All;
}
else
{
 model.Error.Add(rutaRespuesta.Error);
}
Rastreo_Ruta_GetAllResponse rastreo_Ruta_GetAllResponse = null;
Rastreo_Ruta_GetAllRequest rastreo_Ruta_GetAllRequest = new Rastreo_Ruta_GetAllRequest()
{
Codigo_Sesion = DatosSesion.Codigo_Sesion,
user = user,
fecha = fecha,
};
if (SBClient.dbRastreo_Ruta_GetAll(rastreo_Ruta_GetAllRequest, out rastreo_Ruta_GetAllResponse))
{
model.rutaRastreosList = rastreo_Ruta_GetAllResponse.List_Ruta_Rastreo_All;
}
 else
 {
 if (fecha == "")
 {
 var error = new
 {
 error = "Lo sentimos no hay ruta registrada"
 };
 return Json(error, JsonRequestBehavior.AllowGet);
 }
 model.Error.Add(rutaRespuesta.Error);                   
 }
 return View(model);
 }
 catch (Exception e)
 {
 model.Error.Add(new Error() { Message = e.Message, Code = "CATDETCRED" });
return View(model);
}
}
}

View

@model Models.RutaRastreoModel
<select class="form-control" name="user" id="user"  >
<option></option>
@{
if (Model.UsersList != null)
{
foreach (Users user in Model.GestoresList)
{
<option value="@user.id">@user.Nombre</option>
}
}
else
{
<option value="0"> No hay usuarios </option>
}
}
</select>
</div>

<div class="col-md-5">
<input type="date" class="form-control" id="Fecha" placeholder="Fecha" required pattern="[0-9]{2}-[0-9]{2}-[0-9]{4}" />
<span class="validity"></span>
</div>
<div class="col-md-2">
      
<a href="#" class="btn btn-link dropdown-toggle" name="verRuta" id="verRuta" style="font-size:20px" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" title="Ver">
<span class="fa fa-search">Ver</span>
</a>
      
</div>
</div>

<div id="map"></div>

<script type="text/javascript">
    var map;
    var latitude;
    var longitude;
    var center;
    var mapOptions;

    //Mostrar ubicacion actual
    function initMap(posicion) {

         latitude = posicion.coords.latitude;
         longitude = posicion.coords.longitude;

         center = new google.maps.LatLng(latitude, longitude);

            mapOptions = {
                zoom: 13,
                center: center
            };

            map = new google.maps.Map(document.getElementById('map'), mapOptions);

            var marker = new google.maps.Marker({
                map: map,
                position: center
            });
    }

    function error(){
        alert(["No se encontro la ubicacion actual"].join('/'));
    }

    navigator.geolocation.getCurrentPosition(initMap, error);


    //ver ruta
    $("#verRuta").on('click', function (evt) {
        evt.preventDefault();
       
        var fechas = new Date(""); //07/08/2018 12:58:43

        var user = $('#user').val();

        var fecha =  $("#Fecha").datepicker({ minDate: '01/01/2018', dateFormat: 'dd/MM/yyyy' }).val();

           var url="@Url.Action("VerRuta", "Informes")" ;
           var data= {
               user: user,
               fecha: fecha
           }

//De acuerdo al usuario y fecha seleccionada debe mostrar los markers en un mapa en un modal         
           $(".Cargando").css({ 'display': 'block' });
           $('#LocalizacionModal').load('@Url.Action("VerRuta", "Informes")/' + data , function () {
               $(".Cargando").css({ 'display': 'none' });
               $('#LocalizacionModal').modal('show');
           });
       }
    });
</script>
    @if (Model.Error != null){
        foreach (Error error in Model.Error)
    {
        @:console.log("@error.Message Codigo: @error.Code");
    }
    }

Route view in a modal

@model Models.VerRutaModel

<style type="text/css">
#map {
    height: 100%;
    }
</style>

<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close fa fa-close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title" id="VerRutaModal"> Usuario: @Model.iduser, Fecha: @Model.Fecha[0]</h4>
</div>
<div class="modal-body" style="height: 400px;">
<div id="map"></div>  
</div>
<div class="modal-footer text-right">
<button type="button" class="btn btn-primary" data-dismiss="modal">Aceptar</button>
</div>
</div>
</div>


<script type="text/javascript">
    var locations = [];

    var center = new google.maps.LatLng(locations);

    function initialize() {

        @if (Model.rutaRastreosList != null)
      {
          foreach (var ruta in Model.rutaRastreosList)
          {
              <text>
     
        locations = [new google.maps.LatLng(parseFloat(@ruta.Gps_Latitud), parseFloat(@ruta.Gps_Longitud))];


        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: center,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(locations[i][0]);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }
        </text>
          }
      }
    }
        $('#VerRutaModal').on('shown.bs.modal', function () {
            google.maps.event.trigger(map, 'resize');
            map.setCenter(center);
        });
    
    initialize();
</script>

In the browser console it shows this error: GET link 404 (Not Found)

    
asked by Huntzberger 29.10.2018 в 07:00
source

1 answer

0

How are you?

The load function should be used as follows, according to the jQuery documentation: ( link )

$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

Then, you must change the part where you concatenate the url with the javascript object, to send the parameters correctly:

var data = { 
   user: user , 
   fecha: fecha
}

$('#LocalizacionModal').load('@Url.Action("VerRuta", "Informes")', data , function () {
...
});

Greetings!

    
answered by 29.10.2018 / 15:49
source