为什么模型绑定在我的 POST 操作方法中不起作用? [英] Why is Model Binding not working in my POST action method?

查看:23
本文介绍了为什么模型绑定在我的 POST 操作方法中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 MVC 有一个非常奇怪的问题.我的模型不断被提交为空.而且可能真的很简单,但我就是找不到问题所在.

我的模型如下所示:

公共类 LoginModel{公共字符串用户名;公共字符串密码;}

我的控制器是这样的:

[HttpGet]公共操作结果登录(){返回视图();}[HttpPost]公共操作结果登录(登录模型登录测试){if (loginTest.Username != "x" && loginTest.Password != "y"){ModelState.AddModelError("a", "登录失败.");返回视图(登录测试);}别的{return RedirectToAction("首页", "欢迎");}

}

而且视图也很简单,像这样.

@model LoginSolution.Models.LoginModel@{布局 = 空;}<头><meta name="viewport" content="width=device-width"/><title>登录</title><身体>@using (Html.BeginForm("Login", "Home")){<div><span>用户名:</span>@Html.EditorFor(model => model.Username)<br/><span>密码:</span>@Html.EditorFor(model => model.Password)<br/>@Html.ValidationSummary()<br/><input type="submit" value="登录" name="登录"/>

}

这不是关于安全性或最佳实践的问题.这只是一个关于为什么模型在提交时总是返回空的问题.

解决方案

您的模型包含字段,而不是属性(没有 getter/setter),因此模型绑定器无法设置值.将您的模型更改为

公共类 LoginModel{公共字符串用户名 { 获取;放;}公共字符串密码{获取;放;}}

I have a really wierd issue with MVC. My models keeps getting submitted empty. And it's probably really simple, but I just can't find the issue.

My model looks like this:

public class LoginModel
{
   public string Username;
   public string Password;
}

My controller like this:

[HttpGet]
public ActionResult Login()
{
     return View();
}

[HttpPost]
public ActionResult Login(LoginModel loginTest)
{
      if (loginTest.Username != "x" && loginTest.Password != "y")
      {
           ModelState.AddModelError("a", "Login failed.");
           return View(loginTest);
      }
      else
      {
         return RedirectToAction("Home", "Welcome");
       }

}

And the view is also very simple, like this.

@model LoginSolution.Models.LoginModel
@{
   Layout = null;
}
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Login</title>
    </head>
    <body>
        @using (Html.BeginForm("Login", "Home")) 
        { 
        <div> <span>Username : </span>
            @Html.EditorFor(model => model.Username)
        <br />
            <span>Password : </span>
            @Html.EditorFor(model => model.Password)
        <br />
        @Html.ValidationSummary()
        <br />
        <input type="submit" value="Login" name="Login" />
        </div>
        }
    </body>
    </html>

This is not a question about security or best practice. This is just a question regarding why the model keeps returning itself as empty upon submitting.

解决方案

Your model contains fields, not properties (no getter/setter) so the model binder cannot set the values. Change your model to

public class LoginModel
{
   public string Username { get; set; }
   public string Password { get; set; }
}

这篇关于为什么模型绑定在我的 POST 操作方法中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆