【问题标题】:How to obtain an entered data in a form inside Ajax.ActionLink?如何在 Ajax.ActionLink 中获取表单中输入的数据?
【发布时间】:2016-10-05 22:30:14
【问题描述】:

我的页面很简单。它显示了一张图片并有一个评论部分(这是一个局部视图)。我只希望在提交新评论时刷新部分视图。所以我有这个:

        <tr>
            <td>@Html.TextBox("NewComment")</td>
        </tr>
        <tr>
            @Ajax.ActionLink("Submit", "InsertComment", new
            {
               Id = Model.userParticipation.Id,
               CurrentPosition = 0,
               CurrentComments = Model.currentComments,
               NewCommentText = "???"
            },
           new AjaxOptions
            {
                HttpMethod = "GET",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "CommentSection"
            })
        </tr>

我唯一的问题是我不知道如何将 NewComment TextBox 中输入的文本传递给 NewCommentText 变量(而不是“???”字符串)。任何帮助将不胜感激。

【问题讨论】:

  • 你需要 ajax 开始表单,而不是 ajax.action 链接

标签: javascript jquery ajax asp.net-mvc razor


【解决方案1】:

@Ajax.ActionLink 将为锚标记生成标记(带有 ajaxified 行为)。但是由于您想向服务器提交新评论,因此您需要一个输入字段供用户输入评论和可能的表单。如果您希望此表单提交的 ajaxified 行为,您可以使用 Ajax.BeginForm 辅助方法。

@using (Ajax.BeginForm("InsertComment", "Home", new
{
    Id = Model.userParticipation.Id,
    CurrentPosition = 0,
}, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "CommentSection"
}))
{
    <label>Enter comment</label>
    <input type="text" name="NewCommentText" />
    <input type="submit" />
}
<div id="CommentSection"></div>

这将生成表单标签,其中输入元素的名称属性值设置为“NewCommentText”。

假设您的 InsertComment 操作方法(在 HomeController 内部)具有与输入字段同名的参数以及其他参数(如 IdCurrentPosition),这应该可以工作。

[HttpPost]
public ActionResult InsertComment(string NewCommentText,int Id,int currentPosition)
{
    // to do : Save and return some valid markup
    return Content("To do : Replace this with useful html markup");
}

【讨论】:

  • 酷!很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 2010-12-05
  • 1970-01-01
  • 2012-06-05
相关资源
最近更新 更多