我无法从cshtml页面中的表单获取值传递给我的控制器。

huangapple go评论70阅读模式
英文:

I am unable to get the values from a form from cshtml page to my controller

问题

<form action="Home/Book" method="Post">
   <input type="text" id="Name" placeholder="Name">
   <input id="Email" type="text" placeholder="Email">
   <input id="Number" type="number" placeholder="Mobile Number">
   <textarea id="Comment" placeholder="comment here"></textarea>
   <button type="submit">Submit</button>
</form>

这是我的控制器代码

public IActionResult Book(Book obj)
{
    string name = obj.Name;
    name = name + "测试值是否存在";
    return View();
}

在此处输入图片描述

英文:

I am getting null values in my controller after the form is submitted to the code

&lt;form action=&quot;Home/Book&quot; method=&quot;Post&quot;&gt;
   &lt;input type=&quot;text&quot; id=&quot;Name&quot; placeholder=&quot;Name&quot;&gt;
   &lt;input id=&quot;Email&quot; type=&quot;text&quot; placeholder=&quot;Email&quot;&gt;
   &lt;input id=&quot;Number&quot;type=&quot;number&quot; placeholder=&quot;Mobile Number&quot;&gt;
   &lt;textarea id=&quot;Comment&quot; placeholder=&quot;comment here&quot;&gt;&lt;/textarea&gt;
   &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;

This is my controller code

public IActionResult Book(Book obj)
{
string name =obj.Name;
name = name + &quot;testing if value is there&quot;;
return View();
}

enter image description here

答案1

得分: 1

你需要使用 name 属性来绑定表单中的数据,请将您的输入更改为:

<input type="text" id="Name" name="Name" placeholder="Name">

或者如果您正在使用 asp.net core mvc,您可以使用标签助手 asp-for,将您的输入更改为:

<input type="text" asp-for="Name" placeholder="Name">

asp-for="Name" 将自动在 HTML 中生成 id="Name"name="Name"

英文:

You need to use name attribute to bind data in the form, please change your input to:

&lt;input type=&quot;text&quot; id=&quot;Name&quot; name=&quot;Name&quot; placeholder=&quot;Name&quot;&gt;

or if you are using asp.net core mvc, You can use tag hepler asp-for,change your input to:

&lt;input type=&quot;text&quot; asp-for=&quot;Name&quot; placeholder=&quot;Name&quot;&gt;

asp-for=&quot;Name&quot; will generate to id=&quot;Name&quot; name=&quot;Name&quot; automatically in html.

答案2

得分: 0

你应该为你的操作设置HttpPost属性。默认情况下,该操作似乎是GET方法,而不是POST方法。像这样做:

[HttpPost]
public IActionResult Book(Book obj)
{
string name = obj.Name;
name = name + "testing if value is there";
return View();
}

英文:

You should set HttpPost attribute for your action. By default, the action seems to be the get method, not the post method. do like this:

**[httpPost]**
public IActionResult Book(Book obj)
{
string name =obj.Name;
name = name + &quot;testing if value is there&quot;;
return View();
}

huangapple
  • 本文由 发表于 2023年2月6日 14:03:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定