简体   繁体   English

将值发布到webapi控制器

[英]Post value to webapi controller

Here is my WebAPi controller and html form. 这是我的WebAPi控制器和html表单。 The request is correctly routed to the method in the controller by myValue is always null. 通过myValue将请求正确路由到控制器中的方法始终为null。 I thouht this was a valid way to post getting it from some tutorials. 我认为这是从一些教程中发布它的有效方法。

Controller: 控制器:

[Route("add")]
public string Post([FromBody]string  myValue)
{
    return string.Format("HAIAA: [{0}]" , myValue);
}

View: 视图:

<form id="formOne" method="post" action="ninja/add">
    <input type="text" name="myValue" /> 
    <input type="submit" value="submit" />
</form>

You cannot POST a simple type parameter using an HTML form to a Web API action. 您不能使用HTML表单将简单类型参数POST到Web API操作。 Either use a complex type containing your parameter: 使用包含参数的复杂类型:

public class MyFormData {
    public string myValue { get; set; }
}

Changing your controller signature: 更改控制器签名:

[Route("add")]
public string Post([FromBody]MyFormData data)
{
    return string.Format("HAIAA: [{0}]" , data.myValue);
}

Or use AJAX for POSTing the single value to your action: 或者使用AJAX将单个值发布到您的操作:

$('#formOne').submit(function () {
    $.post('ninja/add', { "": $('input[name=myValue]').val() })
        .success(function () {
            //do something
        })
        .error(function () {
            //show error
        });
    return false;
});

There are caveats to using post parameters. 使用post参数有一些警告。

Here is the best resource I have found: 这是我找到的最好的资源:

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/ http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Most likely: 最有可能的:

// POST api/values
public string Post([FromBody]string value) {
  return value;
}

and this weirdness: 而这种古怪:

the value you need to send over needs to be 您需要发送的值需要

{ '': value }

this is the jquery 这是jquery

$.post('ninja/add', { '': value });

Not exactly sure how to fix it in your example........but I think I am giving you the correct value to try to send. 不完全确定如何在你的例子中修复它........但我认为我给你正确的值来尝试发送。

I had the same problem once, and it worked for me to use System.Net.Http.Formatting.FormDataCollection , which takes an object representing the data sent as application-x-www-form-urlencoded 我曾经遇到过同样的问题,并且我使用System.Net.Http.Formatting.FormDataCollection ,它接受一个表示作为application-x-www-form-urlencoded发送的数据的对象

Try 尝试

public string Post(System.Net.Http>formatting.FormDataCollection data)
{
    return string.Format("HAIAA: [{0}]" , data.Get("myValue"));
}

You can try this way. 你可以试试这种方式。

[Route("add")]
        public string Post(System.Net.Http.Formatting.FormDataCollection myValue)
        {
            NameValueCollection nvc = form.ReadAsNameValueCollection();
            string value = nvc.Get("myValue");
            return string.Format("HAIAA: [{0}]", value);
        }

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

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