1

Good day all, what would be the best way to read a value from a text box in a view and to cast it into an integer in the corresponding controller?

View:

@{
    ViewBag.Title = "Index";
}

<h2>Administration</h2>

<p>
    Page number:
    @Html.TextBox("pageNumber")

    @Html.ActionLink("Fetch stats", "FetchStats", "Admin", null,
             new { @style = "text-transform:capitalize;" })


</p>

Controller:

public ActionResult FetchStats(int pageNumber)
    {
    CurrentGameNumber = pageNumber;
    [...]

    return View("Index");

}

2 Answers 2

2

Here's a simple example. We'll add a textbox named "PageNumber" to the form within our View to post data to our FetchStats action method. MVC will take care of all of the plumbing, instantiating the controller and calling the FetchStats action method while provide pageNumber as an integer.

View

@{
    ViewBag.Title = "Index";
}

<h2>Administration</h2>

@using (Html.BeginForm("FetchStats", "Admin")) {    
<p>
    Page number:
    @Html.TextBox("pageNumber")

    <input type="submit" value="Fetch Stats" />
</p>
}

Action Method

[HttpPost]
public ActionResult FetchStats(int pageNumber)
{
    CurrentGameNumber = pageNumber;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I get this error : The parameters dictionary contains a null entry for parameter 'pageNumber' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult FetchStats(Int32)' in 'NHLStats2.Controllers.AdminController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
Can you update your question with a snippet from your view including the form and the PageNumber textbox?
I've updated my answer. It this case form is required for us to issue the post to the FetchStats(int pageNumber) action method. That's also why I added the submit button. To use an action link, you would have to use some client-side scripting (likely jQuery) to modify the href of the link to perform a GET to the FetchStats method and include ?pageNumber=[PAGENUMBERHERE] as a query string parameter.
Works perfectly. Simple and efficient!
0

You can use either HttpPost with AJAX or regular function for that. Basically you need to create a model and then a text field that corresponds to the model variable. Then you can easily manipulate your model data in the Controller Action method. Please check this link. The author displays a way of creating a contact form which is basically your problem in a more expanded way : http://derans.blogspot.com/2011/05/contact-form-revisited-with-aspnet-mvc.html. I hope this helps.

Comments

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.