开发者

How to update textbox value

I have a textbox in my View. I input a number into the textbox, and then i want the controller to multiply the number and put the result into the textbox.

How can I do that?

This is what i have done already. Let's start with the View:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <html xmlns="http://www.w3.org/1999/xhtml" >
            <head runat="server">
                <title>Index</title>
            </head>
            <body>
                <div>
                    <h2>Please enter a number</h2>

                    <% using (Html.BeginForm()) { %>

                        <%=Html.TextBox("number")%>

                        <input type="submit" value="Index" name ="Index" />

                    <% } %>
                </div>
            </body>
        </html>

As you can see I have a simple textbox and button.

This is my controller:

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(int number)
        {
            number = number * 2;
            ViewData["number"] = number;
            return View(Vie开发者_运维技巧wData);
        }
    }
}

But nothing really happens. Yeah, I see the Post is being done, and the coded steps into public ActionResult Index(int number). I see that the number is taken from the textbox, it's multiplied correctly.

I've tried using ViewData as you can see. I've also used TempData. This is another code for the textbox in the View I've tried:

<%=Html.TextBox("number", ViewData["number"])%>

But it doesn't matter. The textbox doesn't get updated with the new value. How can I do that?


Try

    [HttpPost]
    public ActionResult Index(int number)
    {
        number = number * 2;
        ViewData["id"] = number;
        ModelState.Clear(); // this is the key, you could also just clear ModelState for the id field
        return View(ViewData);
    }

You can also just use a regular html input instead of the HtmlHelper and your code would work as expected.

The default behavior of the Html helper is biting you. It looks for data in ModelState collection before using what is in ViewData. The reasoning is the normal case is a POST > Validation Fail > Return View, so showing the data the user entered is the intended behavior.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜