Kosta
Kosta

Reputation: 43

Request.Form.GetValues does not work in ASP.NET Core

I've got this piece of code here :

if (Request.Form.GetValues("multipleTags") is not null)
     selectedTags = Request.Form.GetValues("multipleTags").ToList();

How do I implement this in .NET 5?

The error I'm getting is that there is no GetValues method available.

Upvotes: 2

Views: 12436

Answers (1)

Tiny Wang
Tiny Wang

Reputation: 16066

When using mvc, I agree with @mxmissile to bind a model in the view and receiving data by model in your controller. Some details in this official document.

And alongside your question, I set a form in my view like this:

@{
}

<form id="myForm" action="hello/getForm" method="post">
    Firstname: <input type="text" name="firstname" size="20"><br />
    Lastname: <input type="text" name="lastname" size="20"><br />
    <br />
    <input type="button" onclick="formSubmit()" value="Submit">
</form>

<script type="text/javascript">
    function formSubmit() {
        document.getElementById("myForm").submit()
    }
</script>

And this is my controller method, when using get method, we gather data from querystring(Request.Query) while using post method we get data in request body(Request.Form):

using Microsoft.AspNetCore.Mvc;

namespace WebMvcApp.Controllers
{
    public class HelloController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public string getForm() {
            var a = HttpContext.Request.Query["firstname"].ToString();
            var b = HttpContext.Request.Query["lastname"].ToString();
            var c = HttpContext.Request.Query["xxx"].ToString();
            var d = HttpContext.Request.Form["firstname"].ToString();
            var e = HttpContext.Request.Form["lastname"].ToString();
            var f = HttpContext.Request.Form["xxx"].ToString();
            return "a is:" + a + "  b is:" + b + "  c is:" + c +" d is:"+d+" e is"+e+" f is:"+f;
        }
    }
}

Upvotes: 3

Related Questions