简体   繁体   English

为什么尝试 POST 时我的模型属性为空?

[英]Why are my model properties null when trying to POST?

So I'm trying to create a login page and I've created a form that posts to a action inside the controller.所以我正在尝试创建一个登录页面,并且我创建了一个表单,该表单发布到控制器内的操作。

This is what the controller looks like, very simple, just for testing purposes.这就是控制器的样子,非常简单,仅用于测试目的。

public ActionResult Verify(User account)
{
    var s = account;
    if (db.Users.Any(o => o.Username == ""))
    {
        // Match!
    }
    return Redirect("https://google.se");
}

And here is the HTML这是 HTML

<form id="form1" method="post" action="Verify">
    <!-- Input and Submit elements -->
    <div class="form-group">
        <input type="email" class="form-control form-control-user" id="Username" name="Username" aria-describedby="emailHelp" placeholder="Enter Email Address...">
    </div>
    <div class="form-group">
        <input type="password" class="form-control form-control-user" name="PasswordHash" placeholder="Password">
    </div>
    <a href="Verify" type="submit" class="btn btn-primary btn-user btn-block" >
        Login
    </a>
    <hr>
</form>

When I click Login it does invoke the Verify action, however the parameter I'm passing in account all the properties are null and I'm not sure why.当我单击Login它确实调用了Verify操作,但是我在account传递的参数所有属性都为空,我不知道为什么。

You are not really submitting the form, unless some javascript event does that for you.您并没有真正提交表单,除非某些 javascript 事件为您执行此操作。

Try changing尝试改变

<a href="Verify" type="submit" class="btn btn-primary btn-user btn-block" >
    Login
</a>

to a submit button instead改为提交按钮

<button type="submit" class="btn btn-primary btn-user btn-block" >
     Login
</button>

When you use a link then you are making a GET request which wont post your form data to the controller, in chrome you can see that for yourself in developer tools/network, open that and then click Login, this should result in the Verify request showing up in the list of requests.当您使用链接时,您正在发出一个 GET 请求,该请求不会将您的表单数据发布到控制器,在 chrome 中,您可以在开发人员工具/网络中看到自己,打开它,然后单击登录,这应该会导致验证请求出现在请求列表中。

If you really want to use a link and not a submit button, then you can add a bit of javascript to submit your form, either by adding a event handler or submitting the form directly from the link's onClick method.如果您真的想使用链接而不是提交按钮,那么您可以添加一些 javascript 来提交表单,方法是添加事件处理程序或直接从链接的 onClick 方法提交表单。

<a href="Verify" onclick="document.getElementById('form1').submit();" class="btn btn-primary btn-user btn-block" >
    Login
</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM