views:

27

answers:

2

I just started ASP.NET MVC (coming from WebForms) and I'm struggling with some really basic concepts.

I want to create a single page that uses a textbox for date input. I would like the date input to be passed to the index of my controller which looks like this:

  public ActionResult Index(int month,
                              int day,
                              int year){

        var visitors = visitorRepoistory.FindVisitorsByDate(month, day, year).ToList();

        return View("Index", visitors);
    }

Up to this point I have used scaffolding with strongly typed views so everything was kind of glued together for me.

What would/should my view look like? Would I use an actionlink (this is a get request after all, right?) and not a submit button.

Thanks.

A: 

EDIT after comment:

Simplest way is to make the search input page post (not get) back to some other method, parse the date out, then redirect to the Action you have specified.

If you want to do it through get, then you can use some Javascript trickeration to link to whatever they type in, but I recommend the former.

Shlomo
You can create a form that does a get request using the method attribute.
ZippyV
+2  A: 

I thought about this for a while before trying to come up with an answer. What threw me initially was the concept of turning a single text input string into it's month, day, and year components. In ASP.NET MVC, it would be much easier to just accept the string for the date. This way, your code changes to:

public ActionResult Index(string date) {
   try
   {
      DateTime dtDate = DateTime.Parse(date);
      var visitors = visitorRepoistory.FindVisitorsByDate(dtDate.month, 
                     dtDate.day, dtDate.year).ToList();

      return View("Index", visitors);
   }
   catch (FormatException)
   {
     //String was not a valid date/time
   }
}

Are there ways to split it up into 3 ints? I'm sure. But to me, this would be the easiest/quickest way to the goal.

So in the view, you'll have your form looking something like this:

<% using(Html.BeginForm("VisitorSearchController", "Index")) { %>
Enter a date: <%= Html.TextBox("date") %>
<input type='submit' value='Search' />
<% } %>

Where "VisitorSearchController" is the name of the controller you want to post back to. Of course, "Index" is the method you're posting to. I'd stick with the submit button for now unless you're trying to get a LinkButton equivalent on the page. But you can save the "prettying up" part after functionality, right?

Edit: Added view code to the answer.

villecoder
Thanks, but can you go into the view part a little more? Connecting my view to the controller is what's tripping me up. I'm not sure where to start.
Beavis
You're welcome. I've added the view code to the original answer.
villecoder