简体   繁体   English

在C#中,提交表单字符串输入为null

[英]Submit form string input is null in c#

In my javascript I have: 在我的JavaScript中,我有:

 function reset() { document.getElementById("login").submit(); } 

The request then looks like: 该请求如下所示: 在此处输入图片说明

I'm submitting that to .NET api: 我将其提交给.NET api:

 public async Task<HttpResponseMessage> Reset([FromBody]string login) {} 

and the login string is null. 并且login字符串为null。 Is the request I am making wrong? 我提出的要求有误吗? Or am I accepting it wrong? 还是我接受错了? I'd like to just send abcdefr instead of login=abcdefr 我只想发送abcdefr而不是login=abcdefr

my html: 我的html:

 <div id="reset_password_panel"> <form name="reset-pasword" id="reset-pasword" action="/Reset" method="POST"> <label for="user">User</label> <div><input style="width: 100%" type="text" placeholder="User" id="login" name="login" required /> </div> <div style="width: 100%; display: inline-block;margin-top: 10px;"> <div style="float: left; margin-right: 20px"><button id="btn_login" class="button" onclick="resetPassword()" type="submit">Reset</button> </div> </div> </form> </div> 

If I create class: 如果我创建课程:

 public class LoginModel { public string Login {get;set;} } 

and pass it to 并传递给

 public async Task<HttpResponseMessage> Reset([FromBody]LoginModel login) {} 

it works, but is it possible to pass just a string 它有效,但是否可以传递字符串

The request body is actually login=abcdefr , according to the screenshot, therefore you should declare a class to accept it. 根据屏幕截图,请求正文实际上是login=abcdefr ,因此您应该声明一个类以接受它。 If you want to only send a string, consider sending "abcdefr" : 如果你想发送一个字符串,考虑派遣"abcdefr"

$.ajax({
    'type': 'POST',
    'url': '/Reset',
    'contentType': 'application/json',
    'data': JSON.stringify(document.getElementById("login").value),
    'dataType': 'json'
});

Then you can accept it with a string. 然后,您可以使用字符串接受它。

it works, but is it possible to pass just a string 它有效,但是否可以传递字符串

You can pass raw string data to your route, provided the content type is application/json or application/x-www-form-urlencoded , and the parameter type is string ; 如果内容类型为application/jsonapplication/x-www-form-urlencoded ,并且参数类型为string ,则可以将原始字符串数据传递到路由。 anything else and it won't match your route. 其他任何事情都将与您的路线不符。

If your parameter is a model, the model binder will try to map the input (whether JSON or form data) to your model. 如果您的参数是模型,则模型绑定器将尝试将输入(无论是JSON还是表单数据)映射到您的模型。 If it's a string, it will pass you the raw data. 如果是字符串,它将为您传递原始数据。

The problem is, that if you are passing in raw form data, you'll just have to parse out the bits you want (in your case the "login" value) anyway, so you may as well just use a model instead, and let the model binder do it for you. 问题是,如果要传递原始表单数据,则无论如何都只需要解析出想要的位(在您的情况下为“ login”值),因此您也可以只使用一个模型,而让模型活页夹为您完成。

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

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