web-dev-qa-db-ja.com

ASP.NET MVCはテキストボックスの入力値を取得する

テキストボックス入力といくつかのラジオボタンがあります。たとえば、私のテキストボックスの入力HTMLは次のようになります。

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

ユーザがWebページのボタンをクリックしたら、コントローラにデータを渡します。

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

たぶんそれは簡単ですが、私の問題は私がテキストボックスの値を取得し、それをコントローラに渡す方法がわからないということです。テキストボックスの値を読み、ipValue=@[ValueOfTextBox]を介してコントローラに渡す方法を教えてください。

63
user1624552

電子メールテキストボックスを含む単純な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 structure

131
Andrei

あなたは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>
22
Andriy Gubal

これを試して。

表示:

@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;//
}
11

AJAXメソッドを使用する別の方法:

表示:

@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
    ...
}
6

とても簡単にできます。

最初:モデルの例では、この実装の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
 }
0
vartie