[英]Send parameters to controller from view with no form/input
I reached a point in my code where I need to call a method in the controller from the view. 我在代码中到达需要从视图中调用控制器中的方法的位置。
I need to send some parameters with him from DropDownLists and TextBoxes. 我需要从DropDownLists和TextBoxes向他发送一些参数。
I dont want to make a @using (Html.BeginForm...
and an <input>
, I just want to keep a <button>
with a function call there that gathers that info and runs the method. 我不想创建一个
@using (Html.BeginForm...
和<input>
,我只想保留一个<button>
其中包含一个收集信息并运行该方法的函数调用。
Is it possible? 可能吗?
An example of my DDL and Textbox: 我的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" })
My button: 我的按钮:
<button id="btnAddUpdateConfig" name="btnAddUpdateConfig" value="Apply" onclick="ValidateValues()">Apply</button>
JS: 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
});
}
But my function AddUpdate Configs is not being triggered: 但是我的功能AddUpdate Configs没有被触发:
public ActionResult AddUpdateConfigs(int id, string configType, string location, string threshold, string valueType, int limit)
{
return PartialView();
}
I put a breakpoint in the return and is not reached 我在返回中设置了一个断点,但未达到
Something like this should work: 这样的事情应该起作用:
$.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);
}
}
});
}
Here's the controller action: 这是控制器动作:
[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"
});
}
Do an AJAX request when the button is clicked. 单击该按钮时,请发出AJAX请求。
$.ajax({
type: "POST",
url: http://site.com/Controller/Action,
data: data,
success: success,
dataType: dataType
});
See: http://api.jquery.com/jQuery.post/ 参见: http : //api.jquery.com/jQuery.post/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.