pasar el texto de entrada de la vista al controlador

i know there are a lot questions like this but i really cant get the explanations on the answers... here is my view...

<script type="text/javascript" language="javascript">
$(function () {
    $(".datepicker").datepicker({ onSelect: function (dateText, inst) { },
        altField: ".alternate"
    });

});
</script>

@model IEnumerable<CormanReservation.Models.Reservation>
@{
ViewBag.Title = "Index";
}

<h5>
    Select a date and see reservations...</h5>
<div>
    <div class="datepicker">
    </div>
    &nbsp;<input name="dateInput" type="text" class="alternate" />
</div>

i want to get the value of the input text... there's already a value in my input text because the datepicker passes its value on it... what i cant do is to pass it to my controller... here is my controller:

  private CormantReservationEntities db = new CormantReservationEntities();
    public ActionResult Index(string dateInput )
    {
        DateTime date = Convert.ToDateTime(dateInput);
        var reservations = db.Reservations.Where(r=>r.Date==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
        return View(reservations.ToList());
    }

i am trying to list in my home page the reservations made during the date the user selected in my calender in my home page....

preguntado el 11 de mayo de 12 a las 04:05

1 Respuestas

I don't see a Form tag in your View...or are you not showing the whole view? hard to tell.. but to post to your controller you should either send the value to the controller via an ajax call or post a model. In your case, your model is an IEnumerable<CormanReservation.Models.Reservation> and your input is a date selector and doesn't look like it is bound to your ViewModel. At what point are you posting the date back to the server? Do you have a form with submit button or do you have an ajax call that you aren't showing?

Here is an example of an Ajax request that could be called to pass in your date

$(function () {
    $(".datepicker").onselect(function{
          searchByDate();
        })
    });

});

function searchbyDate() {
   var myDate = document.getElementById("myDatePicker");

    $.ajax({
        url: "/Home/Search/",
        dataType: "json",
        cache: false,
        type: 'POST', 
        data: { dateInput: myDate.value },
        success: function (result) {
            if(result.Success) {
               // do something with result.Data which is your list of returned records
            }
        }
    });
}

Your datepicker control needs something to reference it by

<input id="myDatePicker" name="dateInput" type="text" class="alternate" />

Your action could then look something like this

private CormantReservationEntities db = new CormantReservationEntities();

public JsonResult Search(string dateInput) {
    DateTime date = Convert.ToDateTime(dateInput);
    var reservations = db.Reservations.Where(r=>r.Date==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
    return View(reservations.ToList());
    return Json(new {Success = true, Data = reservations.ToList()}, JsonRequestBehaviour.AllowGet());
}

Noticias

If you want to make this a standard post where you post data and return a view then you need to make changes similar to this.

Crear un modelo de vista

public class ReservationSearchViewModel {
    public List<Reservation> Reservations { get; set; }
    public DateTime SelectedDate { get; set; }
}

Modify your controller actions to initially load the page and then be able to post data return the View back with data

public ActionResult Index() {
    var model = new ReservationSearchViewModel();
    model.reservations = new List<Reservation>();
    return View(model);
}

[HttpPost]
public ActionResult Index(ReservationSearchViewModel model) {
    if(ModelState.IsValid)    
    var reservations = db.Reservations.Where(r => r.Date = model.SelectedDate).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
    }
    return View(model)
}

Modify your view so that you have a form to post to the Index HttpPost action

@model CormanReservation.Models.ReservationSearchViewModel

<h5>Select a date and see reservations...</h5>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    @Html.EditorFor(model => model.SelectedDate)
    @Html.EditorFor(model => model.Reservations) // this may need to change to a table or grid to accomodate your data
    <input type="submit" value="Search" />
}

contestado el 11 de mayo de 12 a las 13:05

i dont have both... i thought i could simply pass the value of input text to the controller without the use of form, only by using scripts... - raberaña

You can use a script but the script needs to call the action. This is what an Ajax request does, you tell it which action to call, which data to send and what to do on success or error. The script you have does nothing more than try to call a function that doesn't exist. Otherwise you need a form to hold your datepicker control and a submit button to post to a specific action. In your case your action is Index.. it's not even a method you can post to as it lacks the [HttpPost] attributes. You need to have a look at asp.net/mvc look at the pluralsight vids for learning MVC - cd herrero

should the return type of Search be JsonResult? you are also returning View, i think it would cause errors... - raberaña

No you're not returning a view, you're returning data to your view, it's an Ajax call which means it's an asynchronous request. Have a look at the pluralsight vids. I'm guessing you haven't worked with MVC very much, correct? - cd herrero

See my update in the answer to accommodate being able open view, post data in a ViewModel to controller HttpPost action and return data to view - cd herrero

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.