ASP.NET MVC获取文本框输入值

82

我有一个文本框输入和一些单选按钮。例如,我的文本框输入HTML如下:

<input type="text" name="IP" id="IP" />

当用户在网页上点击一个按钮时,我想将数据传递给我的控制器:

<input type="button" name="Add" value="@Resource.ButtonTitleAdd"  onclick="location.href='@Url.Action("Add", "Configure", new { ipValue =@[ValueOfTextBox], TypeId = 1 })'"/>

也许这很微不足道,但我的问题是我不知道如何获取文本框的值并将其传递给控制器。如何读取文本框的值并通过ipValue = @[ValueOfTextBox]将其传递给控制器?

5个回答

153

简单的ASP.NET MVC订阅表格,带有电子邮件文本框,可以这样实现:

模型

该表格的数据映射到此模型中

public class SubscribeModel
{
    [Required]
    public string Email { get; set; }
}

视图

视图的名称应该和控制器方法的名称相匹配。

@model App.Models.SubscribeModel

@using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.ValidationMessageFor(model => model.Email)
    <button type="submit">Subscribe</button>
}

控制器

控制器负责处理请求并返回适当的响应视图。

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Subscribe(SubscribeModel model)
    {
        if (ModelState.IsValid)
        {
            //TODO: SubscribeUser(model.Email);
        }

        return View("Index", model);
    }
}

这是我的项目结构。请注意,“Home”视图文件夹与HomeController名称匹配。

ASP.NET MVC结构


1
如果我需要传递除文本框值之外的多个参数,例如一个数字来标识控制器中某个东西的类型,那么您的方法是否支持?如果是这样,请告诉我如何操作? - Willy
@AndreiMikhalevich,您能否给一个HTML POST的例子? - Koushik Saha
@user3132179,唯一的区别在于您需要在操作上放置[HttpPost]属性,并显然在表单中使用Post方法。 - Andrei
1
C# 视图中有 (m => m.FirstName),而视图和控制器中有 @Html.TextBox("name")。Html.TextBox 中的 "name" 是否需要与 UserModel 变量匹配?如果不是,这些页面值如何映射到正确的对象属性? - user153923

27

你可以使用jQuery:

<input type="text" name="IP" id="IP" value=""/>
@Html.ActionLink(@Resource.ButtonTitleAdd, "Add", "Configure", new { ipValue ="xxx", TypeId = "1" }, new {@class = "link"})

<script>
  $(function () {
    $('.link').click(function () {
      var ipvalue = $("#IP").val();
      this.href = this.href.replace("xxx", ipvalue);
    });
  });
</script>

19

试一下。

查看:

@using (Html.BeginForm("Login", "Accounts", FormMethod.Post)) 
{
   <input type="text" name="IP" id="IP" />
   <input type="text" name="Name" id="Name" />

   <input type="submit" value="Login" />
}

控制器:

[HttpPost]
public ActionResult Login(string IP, string Name)
{
    string s1=IP;//
    string s2=Name;//
}

如果您能使用模型类

[HttpPost]
public ActionResult Login(ModelClassName obj)
{
    string s1=obj.IP;//
    string s2=obj.Name;//
}

6
另一种方法是使用ajax方法:
视图(View)代码:
@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

控制器:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

1
每次在操作方法中,我都会得到txtValue的null值。 - Harsh Raj

2
你可以很简单地完成它:
第一步:例如,在模型中,你有一个名为User.cs的文件,其中包含以下实现。
public class User
 {
   public string username { get; set; }
   public string age { get; set; }
 } 

我们将空模型传递给用户 - 当用户提交表单时,该模型将填充用户的数据,如下所示。
public ActionResult Add()
{
  var model = new User();
  return View(model);
}

当您通过空用户作为模型返回视图时,它将与您实现的表单结构映射。在HTML方面,我们有以下内容:
@model MyApp.Models.Student
@using (Html.BeginForm()) 
 {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.username, htmlAttributes: new { 
                           @class = "control-label col-md-2" })
            <div class="col-md-10">
                 @Html.EditorFor(model => model.username, new { 
                                 htmlAttributes = new { @class = "form-
                                 control" } })
                 @Html.ValidationMessageFor(model => model.userame, "", 
                                            new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, htmlAttributes: new { @class 
                           = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = 
                                new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { 
                                           @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" 
                 />
            </div>
        </div>
   </div>
}

当你点击提交按钮时,你需要按照以下方式使用它:

[HttpPost]
public ActionResult Add(User user)
 {
   // now user.username has the value that user entered on form
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接