1

如果我正在使用 Ajax.ActionLink 帮助程序,并且我需要将几个参数传递给控制器​​操作,我如何获取未绑定到模型的 TextArea 的值?

例如,我希望用户填写一个 textarea,然后单击 Save,将 textarea 值发送到控制器操作以进行进一步处理。

我使用 ViewBag 吗?如果是这样,我如何将 DOM 元素的值分配给 ViewBag?

4

2 回答 2

3

I've toyed with this problem before, and you can get around it by using Ajax.BeginForm.

Take this follow example:

I have a model Person that one string property for Name.

View

@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");
    }

Using Ajax.BeginForm() allows you to send data up to the controller even if it not bound to a model on the page. You need to make sure that the name property of your Html element is the same name as the parameter that the controller needs.

So if you have the controller method of

public ActionResult SendUp(string Name, string ta)

You will need to have an Html element of with the name Name and ta inside of the Ajax.BeginForm().

To do this you can either write out the entire element:

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

Or you can use the @Html helpers.

@Html.Editor("Name")

When you provide the name for the @Html helper it will set that value to as the id property and to the name property as well.

于 2012-06-28T15:29:29.687 回答
1

ViewBag 是一个服务器端的概念。一旦页面被渲染,它就不存在了。我不知道以声明方式将页面上的字段与操作参数链接。

要做你想做的事,你有两个选择: - 摆脱 Ajax.ActionLink 帮助程序,并编写一些 Javascript(抱歉,我不能真正帮助你) - 改用 Ajax.BeginForm 并将相关字段放在表单中,以便单击提交按钮将通过 ajax 将表单提交回您的操作。

于 2012-06-27T16:34:25.083 回答