asp.net - 如何在 ASP.NET MVC 2 中获取 html.textbox 输入的值

标签 asp.net asp.net-mvc asp.net-mvc-2

我目前有一个 TextBox使用:
<%: Html.TextBox("TextBox1") %>
如何获取输入到 TextBox 中的内容的值作为字符串,以便我可以在整个应用程序中使用该字符串变量?

该 View 遵循页面顶部的继承进行建模。此页面名为“InputNumbersSection”:

<%: Html.TextBoxFor(m => m.Number) %>

和行动:
<%: Html.ActionLink("Get Number!", "DisplayNumbersSection") %>

模型有这个:
 public class NumberModels
    {
        public string Number { get; set; }
    }

Controller 具有以下功能:
public ActionResult DisplayNumbersSection(NumberModels model)
        {

            if (ModelState.IsValid)
            {
                string TextBoxValue = model.Number;
                ViewData["Number"] = TextBoxValue;
            }      
            return View();
        }

我在另一个页面中使用的 ViewData 从 View 中键入的文本框中返回数字。

当我在文本框中输入一些东西时,我没有看到该属性被命中或执行。 “Number”属性始终返回 NULL。似乎它没有接收我在 TextBox 中输入的内容

最佳答案

首先,您应该有一个 View 模型:

public class YourModel
{
    public string YourProperty { get; set; }
}

您将创建初始 View 的 Controller :
public ActionResult YourEvent()
{
    return View(new YourModel());
}

要创建强类型 View ,您需要将以下内容添加到 Page指示:
<%@ Page Title="" Inherits="System.Web.Mvc.ViewPage<YourModel>" %>

然后在您看来,您可以执行以下操作:
<%: Html.TextBoxFor(m => m.YourProperty) %>

然后在您发布表单时在您的 Controller 中:
[HttpPost]
public ActionResult YourEvent(YourModel model)
{
    if (ModelState.IsValid)
    {
         string TextBoxValue = model.YourProperty;
         // do what you want with it
    }            
    // do something
}

强类型 View 是最好的方法,但如果你想快速而肮脏地完成它,你可以随时访问 Request对象并检查 Form .

编辑:添加了强类型 View 定义。

关于asp.net - 如何在 ASP.NET MVC 2 中获取 html.textbox 输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3225762/

相关文章:

.net - 在 beginform 中使用链接而不是按钮

c# - 如何使用现有的 ASP.net 控制台应用程序构建 android 和 ios 应用程序

javascript - 将 MVC javascript 部分正确转换为纯 javascript 文件

javascript - 单页应用程序的验证码

asp.net-mvc - ASP.NET MVC-仅图像+经过身份验证的用户

javascript - 将对象从 .aspx 文件传递​​到 JavaScript 函数

asp.net-mvc - 如何将枚举传递给Html.RadioButtonFor以获取MVC 2 RC 2,C#中的单选按钮列表

c# - 从文件中动态读取资源

c# - 在 C#/ASP.net 中取消注册一个 javascript block

ASP.NET:如何更改验证失败的控件的背景颜色?