[英]how to get a value from textbox and pass it from actionlink to controller
[英]One of the parameters from ActionLink doesn't pass to controller
我正在使用 MVC5。
nrAccount
) 传递给控制器manualDate
)没有。我究竟做错了什么?
<form action="@Url.Action("Update", "Home"))" method="post">
<tr>
<td>
@Html.DisplayFor(modelItem => item.Account)
</td>
<td class="choice">
@Html.TextBoxFor(modelItem => item.PaymentDate, new { @type = "date", @class = "form-control datepicker" })
</td>
<td>
@Html.ActionLink("Save", "Update", "Home", new { nrAccount = item.Account, manualDate = item.PaymentDate },null)
</td>
</tr>
</form>
public ActionResult Update(string nrAccount, DateTime? manualDate)
{
_docs.Update(manualDate, nrAccount);
return RedirectToAction("Index");
}
_docs
的Update
public void Update(DateTime? manualDate, string nrAccount)
{
var toUpdate = GetByAccount(nrAccount);
toUpdate.DATE_MANUAL = manualDate;
_context.SaveChanges();
}
public IEnumerable<CustomersTable> GetAll()
{
return _context.CustomersTable;
}
public CustomersTable GetByAccount(string nrAccount)
{
return GetAll().FirstOrDefault(k => k.FOPKTO_ACCOUNT_ == nrAccount);
}
没有错误出现,只是没有保存到数据库中。 当我调试我的代码时,我看不到传递给变量manualDate
日期,不知道为什么。 但是nrAccount
被正确传递。
用户可以选择日期一 DatePicker:
问题是您在应该使用 POST 时使用了 GET 请求。 并且您的 GET 包含帐户但不包含日期文本框中的日期,因为它只包含初始值而不是用户将其更改为的值。 因此,要修复您应该通过进行以下更改将您的 GET 更改为帖子。
更正您的表单操作,它也有一个可能的括号,即@Url.Action("Update", "Home")
而不是@Url.Action("Update", "Home"))
将HttpPost
属性添加到控制器中的Update
方法。
如评论中所述,替换您的@Action.Link,这将导致 GET,带有将导致 POST 的提交按钮。
为了获得帐号,请为此添加一个隐藏字段。
最后,由于 textboxfor 的工作方式,您需要更改更新方法以接收具有Account
和PaymentDate
属性的对象。
这是一些与您的非常相似的演示代码,以向您展示我的意思。
视图模型
public class HomeViewModel
{
public string Account { get; set; }
public DateTime? PaymentDate { get; set; }
}
控制器
public class HomeController : Controller
{
public ActionResult Index()
{
var item = new HomeViewModel
{
Account = "theAccountNumber",
PaymentDate = null
};
var viewModel = new List<HomeViewModel>()
{
item
};
return View(viewModel);
}
[HttpPost]
public ActionResult Update(HomeViewModel item)
{
//call your _docs method here
return RedirectToAction("Index");
}
}
视图(注意 Account 的隐藏字段)
@model List<AccountDate.Controllers.HomeViewModel>
<table>
@foreach (var item in Model)
{
<form action="@Url.Action("Update", "Home")" method="post">
<tr>
<td>
@Html.DisplayFor(modelItem => item.Account)
@Html.HiddenFor(modelItem => item.Account)
</td>
<td class="choice">
@Html.TextBoxFor(modelItem => item.PaymentDate, new { @type = "date", @class = "form-control datepicker" })
</td>
<td>
<input type="submit" value="Save" />
</td>
</tr>
</form>
}
</table>
按照我的示例,当单击“保存”时,表单中的所有数据都将发布到服务器,并根据需要使用默认模型绑定放入模型中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.