这是我的输入表单,并希望将输入文本值传递给控制器,但值仍然为空到控制器而另一个问题是无法点击我的控制器 动作创建当我更改我的控制器的名称像索引我的操作指向此操作但不能传递值作为参数。我能做什么???
@using (Html.BeginForm("Create", "Account", FormMethod.Post, new { @id = "form-ui", @class = "form-horizontal form-label-left", @novalidate = "true", enctype = "multipart/form-data" }))
{
<div class="form-group">
<label for="txt_fname">First Name:</label>
<input type="text" class="form-control" id="txt_fname">
</div>
<div class="form-group">
<label for="txt_lname">Last Name:</label>
<input type="text" class="form-control" id="txt_lname">
</div>
<div class="form-group">
<label for="txt_email">Email address:</label>
<input type="email" class="form-control" id="txt_email">
</div>
<div class="form-group">
<label for="txt_username">User Name:</label>
<input type="text" class="form-control" id="txt_username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
}
My Account Controller is:
public class AccountController : Controller
{
// GET: Account
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string txt_fname,string txt_lname,string txt_email,string txt_username,string txt_pwd)
{
AccountVM account = new AccountVM();
account._FirstName = txt_fname;
account._LastName = txt_lname;
account._EmailAdress = txt_email;
account._UserName = txt_username;
account._Password = txt_pwd;
//Insert Value
account.CreateAccount();
return View();
}
}
答案 0 :(得分:1)
您需要将用于模型绑定的name
属性和作为键值对发布回控制器操作。因此,请将所有input
元素更改为name属性:
<input type="text" class="form-control" id="txt_fname" name="txt_fname">
注意name="txt_fname"
,现在您的控制器应该有一个名为txt_name
的参数来获取其中的值。
由于您有一个视图模型,您应该按照以下方式发布Model对象。
在视图的顶部声明此视图可以绑定的模型以用于发布和显示:
@model YourNameSpace.ViewModels.AccountVM
@using (Html.BeginForm("Create", "Account", FormMethod.Post, new { @id = "form-ui", @class = "form-horizontal form-label-left", @novalidate = "true", enctype = "multipart/form-data" }))
{
<div class="form-group">
<label for="txt_fname">First Name:</label>
@Html.TextBoxFor(x=>x.txt_fname)
.......
......
</div>
}
,您的操作方法现在只有一个类型为AccountVM
的参数:
[HttpPost]
public ActionResult Create(AccountVM account)
{
//Insert Value
account.CreateAccount();
return View();
}
您也可以在调用CreateAccount
之前添加验证,如:
if(ModelState.IsValid)
{
//Insert Value
account.CreateAccount();
return View();
}
else
{
return View(account);
}