0

我在代码中达到了一个点,我需要从视图中调用控制器中的方法。

我需要从 DropDownLists 和 TextBoxes 与他一起发送一些参数。

我不想制作 a@using (Html.BeginForm...和 an <input>,我只想保留 a<button>的函数调用,该函数调用收集该信息并运行该方法。

可能吗?

我的 DDL 和文本框的示例:

@Html.DropDownListFor(cModel => cModel.QueueMonitorConfigTypeName, Enum.GetValues(typeof(BPM.Website.Models.PathType)).Cast<BPM.Website.Models.PathType>().Select(v => new SelectListItem
                            {
                                Text = v.ToString(),
                                Value = v.ToString()
                            }), new { id = "ddlConfigTypeName" })



@Html.TextBoxFor(cModel => cModel.Location, new { id = "txtbLocation" })

我的按钮:

<button id="btnAddUpdateConfig" name="btnAddUpdateConfig" value="Apply" onclick="ValidateValues()">Apply</button>

JS:

function ValidateValues()
{
        $.ajax({
            type: "POST",
            url: "Storage/AddUpdateConfigs",
            data: ({id: @Model.QueueMonitorConfigurationsID, PathType: $('#ddlConfigTypeName').val(), Threshold:$('#ddlThreshold').val(), ValueType:$('#ddlValueTypeName').val(), Location: $('#txtbLocation').val(), Limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() }),
            dataType: JSON
        });
}

但是我的函数 AddUpdate Configs 没有被触发:

    public ActionResult AddUpdateConfigs(int id, string configType, string location, string threshold, string valueType, int limit)
    {




        return PartialView();
    }

我在返回中放了一个断点,但没有到达

4

2 回答 2

1

像这样的东西应该工作:

$.postify = function(value) {
    var result = {};

    var buildResult = function(object, prefix) {
        for (var key in object) {

            var postKey = isFinite(key)
                ? (prefix != "" ? prefix : "") + "[" + key + "]"
                : (prefix != "" ? prefix + "." : "") + key;

            switch (typeof (object[key])) {
                case "number": case "string": case "boolean":
                    result[postKey] = object[key];
                    break;

                case "object":
                    if (object[key].toUTCString)
                        result[postKey] = object[key].toUTCString().replace("UTC", "GMT");
                    else {
                        buildResult(object[key], postKey != "" ? postKey : key);
                    }
            }
        }
    };

    buildResult(value, "");

    return result;
};

function login() {
    var logonmodel = {
        UserName: $tbUsername.val(),
        Password: $tbPassword.val()
    };
    $.ajax({
        type: "POST",
        url: "/account/logon",
        data: $.postify(logonmodel),
        asynch: true,
        dataType: "json",
        success: function (msg) {
            console.log(msg.state);
            if (msg.state == 'good') {
                window.location.href = msg.url;
            }
            else {
                var $generalLoginError = $('span#generalLoginError');
                var $loginuserNameError = $('span#loginUserNameError');
                var $loginPasswordError = $('span#loginPasswordError');

                $loginuserNameError.html(msg.errors.username);
                $loginPasswordError.html(msg.errors.password);
                if (msg.errors.incorrect != '')
                    $generalLoginError.html(msg.errors.incorrect);
            }
        }
    });
}

这是控制器动作:

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, false);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Json(new { url = returnUrl, message = "", state = "good" });
            }
            else
            {
                return Json(new { url = "/", message = "", state = "good" });
            }
        }
    }

    // If we got this far, something failed, redisplay form
    return Json(new
    {
        url = "/",
        errors = new
        {
            username = (model.UserName == null) ? "required" : "",
            password = (model.Password == null) ? "required" : "",
            incorrect = (!Membership.ValidateUser(model.UserName, model.Password)) ? "The user name or password provided is incorrect." : "",
            //generic = "An error has occurred. If the error persists, please contact the webmaster."
        },
        state = "error"
    });
}
于 2013-06-07T17:41:46.427 回答
0

单击按钮时执行 AJAX 请求。

$.ajax({
  type: "POST",
  url: http://site.com/Controller/Action,
  data: data,
  success: success,
  dataType: dataType
});

见: http ://api.jquery.com/jQuery.post/

于 2013-06-07T17:38:22.073 回答