I have 2 buttons (Save and Preview) in my partial view. This partial view is doing the Ajax post and both of the buttons doing their job fine where Preview is just allowing to preview the widget while Save is saving the data into the DB. Here I have 2 problems
public ActionResult EditWidget(WidgetViewModel viewmodel, string onSave, string onPreview)
{
if(!string.IsNullOrEmpty(onPreview))
{
viewmodel.ButtonName = "Preview";
var parameters = "";
if (!string.IsNullOrEmpty(viewmodel.OverriedParameters))
parameters = viewmodel.OverriedParameters;
else
parameters = viewmodel.DefaultParameters;
return PartialView("Widgets/_Preview", previewViewModel);
}
else if(!string.IsNullOrEmpty(onSave))
{
viewmodel.ButtonName = "Save";
if(ModelState.IsValid)
{
//RedirectToAction("GetPage", "Home", new { Page = pageId
return Json(Url.Action("GetPage", new {Page = pageId}));
}
}
return null;
}
my partial view is as follow
@using (Ajax.BeginForm("EditWidget", "Home", new AjaxOptions { UpdateTargetId = "divPreview", HttpMethod = "POST", OnBegin = "application.getpage.onBeginPreview", OnSuccess = "application.getpage.onSuccessPreview" }))
{
<div class="form-inline">
@Html.LabelFor(x => x.OverriedParameters, "Is Widget Active ?", new { @class = "col-sm-2" })
@Html.TextBoxFor(x => x.OverriedParameters, new { @class = "col-sm-1" })
</div>
<div class="form-inline">
@Html.LabelFor(x => x.DefaultParameters, "Is Widget Active ?", new { @class = "col-sm-2" })
@Html.TextBoxFor(x => x.DefaultParameters, new { @class = "col-sm-1" })
</div>
<div class="form-inline">
<input id="btnSave" name="onSave" type="submit" class="btn btn-primary" style="width:65px" value="Save" />
<input id="btnPreview" name="onPreview" type="submit" class="btn btn-primary" style="width:65px" value="Preview" />
</div>
}
<div id="divPreview" style="margin-top:5px">
</div>
and my onSuccess is as follow
onSuccessPreview: function (data, textStatus, jqXHR) {
// Here i want to find which button is clicked from my partial view.
// On Save button click i want to redirect to the action method in the same controller while on Preview button i don't want to do anything
}
You could add a hidden input:
<div class="form-inline">
<input id="btnSave" name="onSave" type="submit" class="btn btn-primary" style="width:65px" value="Save" />
<input id="btnPreview" name="onPreview" type="submit" class="btn btn-primary" style="width:65px" value="Preview" />
<input type="hidden" id="what-was-clicked" />
</div>
update its value using onclick method in javascript (before submit) and read it in your onSucces:
onSuccessPreview: function (data, textStatus, jqXHR) {
var clickedButton = $("#what-was-clicked").val();
}