如果我使用的是 Ajax.ActionLink 助手,并且我需要将几个参数传递给 Controller 操作,我如何才能获得未绑定(bind)到模型的 TextArea 的值?
例如,我希望用户填写一个文本区域,然后单击“保存”,将文本区域的值发送到 Controller 操作以进行进一步处理。
我使用 ViewBag 吗?如果是这样,我如何将 DOM 元素的值分配给 ViewBag?
请您参考如下方法:
我以前遇到过这个问题,您可以使用 Ajax.BeginForm 解决它。
以下面的例子为例:
我有一个模型 Person,它有一个 Name 的字符串属性。
查看
@model Application.Models.Person
<fieldset>
<legend>Form</legend>
@using (Ajax.BeginForm("SendUp", "Home", new AjaxOptions
{
HttpMethod = "POST",
OnComplete = "window.location.href = 'Index'"
}))
{
<p>
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name)
</p>
<p>
@Html.TextArea("ta")
</p>
<p>
<input type="submit" value="Submit" />
</p>
}
</fieldset>
Controller
[HttpPost]
public ActionResult SendUp(string Name, string ta)
{
string s = ta;
// Process stuff here
// Go to another action or whatever
return RedirectToAction("Index");
}
使用 Ajax.BeginForm() 允许您将数据发送到 Controller ,即使它没有绑定(bind)到页面上的模型。您需要确保您的 Html 元素的 name 属性与 Controller 所需的参数名称相同。
所以如果你有
的 Controller 方法public ActionResult SendUp(string Name, string ta)
您需要在 Ajax.BeginForm() 中有一个名为 Name 和 ta 的 Html 元素。
为此,您可以写出整个元素:
<input type="text" id="Name" name="Name" />
或者您可以使用 @Html 助手。
@Html.Editor("Name")
当您为 @Html 帮助器提供名称时,它会将该值设置为 id 属性和 name 属性。
