【问题标题】:ASP NET MVC 3.0 GET USER INPUTASP NET MVC 3.0 获取用户输入
【发布时间】:2011-01-25 13:11:59
【问题描述】:

从视图获取用户输入到控制器的最佳方式是什么?我的意思是特定输入不像“FormCollection”之类的“object person”或“int value”以及如何在特定时间间隔刷新页面

【问题讨论】:

    标签: .net asp.net asp.net-mvc-3


    【解决方案1】:

    通过编写视图模型:

    public class UserViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    控制器:

    public class UsersController : Controller
    {
        public ActionResult Index()
        {
            return View(new UserViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(UserViewModel model)
        {
            // Here the default model binder will automatically
            // instantiate the UserViewModel filled with the values
            // coming from the form POST
            return View(model);
        }
    
    }
    

    查看:

    @model AppName.Models.UserViewModel
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.FirstName)
            @Html.TextBoxFor(x => x.FirstName)
        </div>
        <div>
            @Html.LabelFor(x => x.LastName)
            @Html.TextBoxFor(x => x.LastName)
        </div>
    
        <input type="submit" value="OK" />
    }
    

    【讨论】:

      【解决方案2】:

      例如,如果您的视图是使用“Person”类进行强类型化的:

      public class Person
      {
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public int Age { get; set; }
      }
      

      然后在你的视野中:

      @model MyMVCApp.Person
      @using(Html.BeginForm())
      {
          @Html.EditorForModel()
          // or Html.TextBoxFor(m => m.FirstName) .. and do this for all of the properties.
          <input type="submit" value="Submit" />
      }
      

      然后你会有一个处理表单的动作:

      [HttpPost]
      public ActionResult Edit(Person model)
      {
          // do stuff with model here.
      }
      

      MVC 使用所谓的ModelBinders 获取该表单集合并将其映射到模型。

      要回答您的第二个问题,您可以使用以下 JavaScript 刷新页面:

      <script type="text/javascript">
      // Reload after 1 minute.
      setTimeout(function ()
      {
          window.location.reload();
      }, 60000);
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        相关资源
        最近更新 更多