Reputation: 4323
I have multiple ajax forms on page that cointain same elemets, I have jquery function on succes that searches childrean elements of form and updates, but I need to somehow pass Id of the form that sent request to the controller along with other values from form, what is the best way to do this? Maybe add hidden field to form and on page load get parentid and put it in this field with jQuery. But I don't know jquery that well to do that.
@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');
}
}
UPDATE : this is partial view that gets loaded n times so I can't find out formID until page is rendered in browser.
Upvotes: 0
Views: 8832
Reputation: 1038720
You could give your form an unique id and pass this id to the callback:
@{
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" />
}
now inside the success function you will be able to fetch the JSON result returned by the server and the id of the form:
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');
}
}
Upvotes: 7