如何从Html Action Link控件捕获多个值从用户输入的文本框中传递并发送到Action方法?

时间:2016-02-12 02:44:16

标签: javascript asp.net-mvc-4

我有以下观点:

<div class="form-group">
    @Html.LabelFor(m => m.LoginId, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.LoginId, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.LoginId, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">            
        @Html.ActionLink("Log in", "Login1", null, new { @class = "link" })
    </div>
</div>

这就是javascript:

$(function () {
    $('.link').click(function () {
        var loginid = $("#LoginId").val();
        var pass = $("#Password").val();
        this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
        this.href = this.href + '?password=' + encodeURIComponent(pass); // Something is going wrong here!
    });
});

这是Controller Action方法:

public ActionResult Login1(string loginid,string password)
{
    if (loginid == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    User user = db.Users.Find(loginid);
    if (user == null)
    {
        return HttpNotFound();
    }
    return RedirectToAction("Index", "Products");
}

我输入了loginid = a和密码= b。 但问题是:它发送的是loginid =:a?password = b和password = null。 如何正确发送参数?

2 个答案:

答案 0 :(得分:0)

按下按钮提交按钮,表单会在点击时自动发布,您不必编写任何其他代码。

确保您的文本框名称(而非ids)与您操作中的参数名称相匹配。

答案 1 :(得分:0)

我认为,但我不是专家,该错误在于ajax函数。 '?'造成了问题。当前如下:

this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
this.href = this.href + '?password=' + encodeURIComponent(pass); 

但应该是:

this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
this.href = this.href + '&password=' + encodeURIComponent(pass);