我在页面上有多个ajax表单,它们包含相同的元素,我有成功的jquery函数搜索表单和更新的childrean元素,但我需要以某种方式将发送请求的表单的Id与其他值一起传递给控制器从形式来看,最好的方法是什么?也许添加隐藏字段到窗体和页面加载得到parentid并将其放在这个领域与jQuery。但我不知道jquery做得那么好。
@using (Ajax.BeginForm("Index", "Controller",new AjaxOptions { OnFailure = "error", OnSuccess ="sucess" }))
{
<input type="submit" name="value" class="up" value="1" />
<span class="result">0</span>
<input type="submit" name="value" class="down" value="-1" />
}
public ActionResult Index(int value ,string formID)
{
//do something
}
function sucess(arg) {
var json = $.parseJSON(arg.responseText);
var form = $("form#" + json.FormID);
var up = form.children('input.up');
var down = form.children('input.down');
form.children('span.result').replaceWith(json.Result);
if (json.Result == 1) {
up.addClass('active');
}
if (json.Result == -1) {
down.addClass('active');
}
}
更新:这是部分视图加载了n次,所以在浏览器中呈现页面之前我找不到formID。
答案 0 :(得分:6)
您可以为表单指定一个唯一ID,并将此ID传递给回调:
@{
var formId = Guid.NewGuid().ToString();
}
@using (Ajax.BeginForm("Index", "Controller", null, new AjaxOptions { OnFailure = "error", OnSuccess = string.Format("success(data, '{0}')", formId) }, new { id = formId }))
{
<input type="submit" name="value" class="up" value="1" />
<span class="result">1</span>
<input type="submit" name="value" class="down" value="-1" />
}
现在在success函数中你可以获取服务器返回的JSON结果和表单的id:
function success(json, formId) {
// Remark you don't need to call $.parseJSON here.
// inside the success callback the first argument will already
// represent a parsed object that you can use directly. This obviously
// assumes that your controller action returns JSON:
// return Json(new { Result = 1 });
var form = $("#" + formId);
var up = form.children('input.up');
var down = form.children('input.down');
form.children('span.result').replaceWith(json.Result);
if (json.Result == 1) {
up.addClass('active');
}
if (json.Result == -1) {
down.addClass('inactive');
}
}