CoolArchTek
CoolArchTek

Reputation: 3829

Asp.net MVC - Post data to a controller

I am working on a sample mvc project in which I am trying to post data to a controller. I have posted sample (see below), but if I add [HttpPost] to method I am getting '404' error.

View:

<% using (Html.BeginForm()) { %>
    <%= Html.Telerik().NumericTextBox()
                .Name("NumericTextBox")
                .Spinners(false)
                .EmptyMessage("ID")
    %>
    <input type="submit" value="Submit" />
<% } %>

Controller:

[HttpPost]
public ActionResult GetDetails(int id)
{
    return View();
}

**I also tried,**
[HttpPost]
public ActionResult GetDetails(FormCollection collection)
{
    return View();
}

Route:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Customer", action = "GetDetails", id = UrlParameter.Optional } // Parameter defaults
);

Upvotes: 0

Views: 2539

Answers (2)

McGarnagle
McGarnagle

Reputation: 102723

You'll want the Name to match the parameter on the controller, so I believe it should be like this:

Html.Telerik().NumericTextBox()
            .Name("id")

Notes:

  1. Although you specified UrlParameter.Optional on the id route parameter, it's not truly optional unless you make it nullable (ie, int? id) in the controller action.
  2. Normally you should use GET and not POST for HTTP requests that don't change anything on the server, which seems to be the case here.

Upvotes: 2

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

You should use the second method, but instead of FormsCollection, use:

GetDetails(int NumericTextBox)

The parameter must be the same name as the input box.

Upvotes: 0

Related Questions