获取输入c#mvc的值
本文关键字:的值 c#mvc 输入 获取 | 更新日期: 2023-09-27 17:59:52
我有一些输入框,我需要从中获取值,以便以后可以将它们重定向到特定的控制器,但我不知道如何访问这些值。有人能告诉我如何获得价值观吗?
<form action="@Url.Action("AddSpecific", "Comment", new { AuthorT ="1", WebSiteT = "1", postIdT = 1, TextT = "1",TitleT = "1" })" method="post">
<h1>
<label for="Title">Title</label>
<input name="Title" id="Title" type="text" required />
</h1>
<h1>
<label for="Text">Text</label>
<input name="Text" id="Text" type="text" required />
</h1>
<h1>
<label for="AuthorSite">AuthorSite</label>
<input name="AuthorSite" id="AuthorSite" required />
</h1>
<h1>
<label for="Author">Author</label>
<input name="Author" id="Author" type="text" required />
</h1>
<h1>a
<label for="IdOfPost">IdOfPost</label>
<input name="IdOfPost" id="IdOfPost" type="number" required />
</h1>
<input type="submit" value="Post comment" />
我会使用一个模型来传递并将其用作操作的参数。
您需要更改表单html,这样就不会发送默认值。更改:
<form action="@Url.Action("AddSpecific", "Comment", new { AuthorT ="1", WebSiteT = "1", postIdT = 1, TextT = "1",TitleT = "1" })" method="post">
收件人:
<form action="@Url.Action("AddSpecific", "Comment")" method="post">
MySpecificObject(操作的参数对象)。请注意,属性名称与输入的名称属性匹配,这一点很重要:
public class MySpecificObject
{
public string AuthorSite {get;set;}
public string Title {get;set;}
public string Text {get;set;}
public string Author {get;set;{
public string IdOfPost {get;set;}
}
更新你的评论控制器:
public ActionResult AddSpecific(MySpecificObject mySpecificObject)
{
//mySpecificObject.IdOfPost
//do work
}
此外,如果您决定通过JavaScript和Ajax执行此操作,请检查StackOverflow post:使用Ajax 将表单数据发布到Controller的操作
当您使用声明的属性构建Form时,您的本质上指示了它应该尝试Post的位置。一旦您概述了所述属性,提交按钮将执行到该位置。模型视图控制器将自动执行您的一些请求,因此控制器将指向:
public ActionResult Submit(int id, string name, string email)
{
// Utilize parameters.
}
因此,如果您用与Controller中的参数匹配的name
勾勒表单字段,MVC将尝试将所述字段直接关联到Controller。所以你现在的方法可能根本不需要发生。
您的输入元素应该与控制器上的参数具有相同的名称值
例如,如果你的控制器看起来像这样:
public ActionResult AddSpecific(String AuthorT)
{
//Do Some Actions
return View();
}
您应该有一个具有名称为"AuthorT"的元素的表单:
<form action="@Url.Action("AddSpecific")" method="post">
<h1>
<label for="Title">Title</label>
</h1>
<input name="AuthorT" id="AuthorT" type="text" required />
<input type="submit" value="Post Comment"/>
</form>
如果输入元素的名称值与控制器参数的名称相同,则控制器将获取此值