0

I have a view that has to pass a start date, an end date, and a guestnumbers int to a controller.

The view is this with formatting stripped out ....

    @using (Html.BeginForm("Index", "BookingCalculation", new { BookingFrom = "BookingFrom", BookingTo = "BookingTo", GuestNumbers = "GuestNumbers" },FormMethod.Post)) 
    {
           @Html.JQueryUI().Datepicker("BookingFrom").DefaultDate(DateTime.Today).MinDate(DateTime.Today)
   @Html.JQueryUI().Datepicker("BookingTo").DefaultDate(DateTime.Today).NumberOfMonths(2) 
   @Html.TextArea("GuestNumbers","2") 
    <input type ="submit" value ="submit" />
        }

The Controller is this ....

 public ActionResult Index(string BookingFrom, string BookingTo, int? GuestNumbers) {

I passed the datetime through as a string so it can take null values.

How do I wire up the parameters to pass data through? It always passes null no matter what I set. Yet the two are connected as a click on the Index in (Html.BeginForm("Index" takes me to the method.

It doesn't throw any errors just doesn't pass data across.

As you can tell I am a noob at ASP.net. :-)

1 Answer 1

1

First you should create a view model that represents the data you want to edit and let MVC take care of the binding

public class BookingVM
{
  public DateTime? BookingFrom { get; set; }
  public DateTime? BookingTo { get; set; }

  [Display(Name="Please enter number of guests")]
  [Range(1, 10)] // optional validation
  public int? GuestNumbers { get; set; } // not sure why you would want this to be nullable?
}

BookingCalculationController

public ActionResult Create()
{
  BookingVM model = new BookingVM();
  // You can set default properties here (e.g. model.GuestNumbers = 2;)
  return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(BookingVM model)
{
  if(!ModelState.IsValid)
  {
    // return the view to correct validation errors
    return View(model);
  }
  // its valid so save values and redirect somewhere
  return RedirectToAction("...");
}

View

@model BookingVM
@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
  @Html.ValidationSummary(true)

  @Html.JQueryUI().Datepicker(m => m.BookingFrom)
  @Html.JQueryUI().Datepicker(m => m.BookingFrom)

  @LabelFor(m => m.GuestNumbers)
  @Html.TextBoxFor(m => m.GuestNumbers)
  @Html.ValidationMessageFor(m => m.GuestNumbers)

  <input type ="submit" value ="submit" />
}

Don't forget to include the jquery, jquery.validate and jquery.validate.unobtrusive files if you want client side validation

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for such a comprehensive answer! There is far more to this than I realised :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.