【问题标题】:Binding in ASP.NET MVCASP.NET MVC 中的绑定
【发布时间】:2013-02-01 22:21:44
【问题描述】:

我的问题是关于 MVC 中的绑定。你能帮我吗?

我的控制器:

public class TestController : Controller
 {
        //
        // GET: /Test/
        [HttpGet]
        public ActionResult Index()
        {
            return View(new TestModel());
        }
        public ActionResult Index(TestModel test)
        {
           return View(test);
        }
 }

我的看法:

@model MvcApplication1.Models.TestModel

@using (Html.BeginForm())
{
@Html.TextBoxFor(x => x.test) // or x.Test
<input type="submit" value="Set"/>
}

我的模特:

public class TestModel
{
public string test { get; set; } // or Test{get;set;}
}

据我了解,问题与控制器中参数“test”的名称有关。我刚刚将其更改为“模型”并且绑定正在工作。但它在原始状态下不起作用(参数名称为'test'),'test'参数为空。

请让我理解为什么绑定在当前示例中不起作用。非常感谢!

【问题讨论】:

  • 模型中测试参数的值为空,因为它从未被设置为任何值。
  • 我不明白为什么。我的帖子正文有 test=value。首先,活页夹正在帖子正文(以及其他一些地方)中搜索“test.test”。之后它应该搜索简单的“测试”并绑定到模型。正确的 ?或者,我认为绑定过程是错误的..

标签: asp.net-mvc binding


【解决方案1】:

您的第二种方法需要[HttpPost] 属性。您也不能使用test 作为变量名,因为它与您尝试绑定的类的属性名称相同; ModelBinder 无法确定使用哪个。您的代码如下所示:

public class TestController : Controller
 {
        //
        // GET: /Test/
        [HttpGet]
        public ActionResult Index()
        {
            return View(new TestModel());
        }

        //
        // POST: /Test/
        [HttpPost]
        public ActionResult Index(TestModel testModel)
        {
           return View(testModel);
        }
 }

【讨论】:

  • 它不工作。动作“Index(TestModel test)”中的测试变量为空。默认绑定仍然不起作用。
  • 你在修改ModelBindingContext吗?
  • 不,这只是我添加到 Empty MVC4 New 项目中的代码。我添加了这些控制器、视图和模型,仅此而已。可能是默认绑定的一些具体实现,我不知道。
  • 天啊!我刚刚意识到您的类中的属性名称与您的 Index 方法中的变量名称相同。查看这个问题的答案:stackoverflow.com/questions/7508896/…
  • 是的,我明白了。我在一些书中读到了默认绑定,但我找不到一些关于它的注释。你能提供一些关于它的参考吗?据我所知,首先 - binder 在某些地方搜索 test.test(在帖子、查询字符串、路由中的默认值等),其次 - 应该只搜索 - 'test' 并将其绑定到我的模型:(
猜你喜欢
  • 2014-08-08
  • 1970-01-01
  • 2021-05-20
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多