How to update an MVC partial view with regular Ajax - ajax

I have an Ajax form that updates the partial view it's in, but I need it to update a second partial view as well. I'd like to do this without merging them both into one view and updating that.
I think my best bet is to use a regular jQuery Ajax call on the form's onsuccess, but I don't know what parameters to use so I can just call a Controller Action that returns the partial to have it work.
My form is set up with
#using (Ajax.BeginForm("UpdateDateRange",
new { name = Model.Modules[i].Name },
new AjaxOptions { UpdateTargetId = Model.Modules[i].Name.Replace(" ", "_") + "_module" }
))
{ [Input fields] }

In your onSuccessmethod you can make another ajax call.
So for example in your OnSuccessMehtod call "MethodX"...which would do a ajax call and update a div on your page with returned result
var MethodX = function(id)
{
$.get("ActionName?id=" + id, function (result) {
$("#myAnotherdiv").html(result)
}, 'html');
}

In response to ajax call you can send two partial view that you want with this helper:
public static class MvcHelpers
{
public static string RenderPartialView(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
And in controller:
return Json(new { view1 = this.RenderPartialView(...), view2 = this.RenderPartialView(...) });
and in success you can get two partialView and replace them with old ones:
function success(data)
{
$("someSelectorToSelectPartial1").html(data.view1);
$("someSelectorToSelectPartial2").html(data.view2);
}

Related

How to get urlValue in Ajax Post OnSuccess function from controller

I'm developing an MVC Login application
I wanted to redirect to MainPage URL (Ex:-www.amazon.in) from controller to view once the user is validated successfully
Here my Code
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
var result = await SignInManager.PasswordSignInAsync(model.StoreNumber, model.UserName, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case MolSignInStatus.Success:
return RedirectToLocal(returnUrl);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
var returnPath = new Uri(returnUrl).AbsolutePath;
if (Url.IsLocalUrl(returnPath))
{
//return Redirect(returnUrl);
return JavaScript("window.location = 'www.amazon.in'");
}
return RedirectToAction("Index", "StoreRegistration");
}
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions { HttpMethod = "POST", OnSuccess = "successOfAddition", OnFailure = "failureOfAddition" }
))
{
}
<script type="text/javascript">
function successOfAddition(data) {
if (data.MessageType == '') {
}
}
function failureOfAddition(data) {
debugger;
showAlert(data.MessageType, data.Message);
}
</script>
Here i want to get the returnUrl value from RedirectToLocal ActionResult method of controller, basically i wanted to redirct the user to new web site on succesfull login.
The below code is not working with Ajax Post
return Redirect(returnUrl);
so I'm trying to use
return JavaScript("window.location = + 'www.amazon.in'");
It works fine but instead of hard coding the url value i wanted it to pass to my view on OnSuccess function.

DevExpress - Ajax form return null object

i work with Ajax.BeginForm
#model Shared.DataContracts.ConfigurationTransports
#using (Ajax.BeginForm("Save", "ConfigurationTransports",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace
}))
{
Html.RenderPartial("~/Views/ConfigurationTransports/ConfigurationPartialContent.cshtml", Model);
}
And my easy form
#model Shared.DataContracts.ConfigurationTransports
#Html.DevExpress().Label(s =>
{
s.Name = "Id";
s.ClientVisible = false;
}).Bind(Model.Id).GetHtml()
#Html.DevExpress().CheckBox(settings =>
{
settings.Name = "checkBoxUseStop";
settings.Properties.ValueUnchecked = 0;
settings.Properties.ValueChecked = 1;
settings.Text = Resources.UseStops;
}).Bind(Model.UseStop).GetHtml()
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnSave";
settings.UseSubmitBehavior = true;
}).GetHtml()
When I click save a post to method Save and parameter ConfigurationTransports is empty without value, but if i load my form i have there values from my send object.
public ActionResult Save(ConfigurationTransports transport)
{
//Some logic method
return View("Index", preprava.GetData());
}
I read a lot of topic on devexpress forum, but i cant find solution.
Do you have any idea?
thx
decorate your Action with [HttpPost] Annotation
[HttpPost]
public ActionResult Save(ConfigurationTransports transport)
{
//Some logic method
return View("Index", preprava.GetData());
}

ActionLink to submit Model value

I want my Ajax.ActionLink to pass a viewModel property to action.
Here is my ViewModel
public class ViewModel
{
public string Searchtext { get; set; }
}
My .cshtml
#Ajax.ActionLink("Bottom3", "Bottom3",new { name = Model.Searchtext}, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "pointsDiv"
})
using(Html.BeginForm("Bottom3", "Home", FormMethod.Get))
{
#Html.TextBoxFor(x => x.Searchtext)
<button type="submit">Search</button>
}
<div id="pointsDiv"></div>
}
My Controller action:
public PartialViewResult Bottom3(string name)
{
var model = db.XLBDataPoints.OrderBy(x => x.DataPointID).Take(3).ToList();
return PartialView("Partial1", model);
}
But the name parameter passed to the action is always null. How do I solve this?
In your code... you have 2 different ways of posting to the server: the link and the form button.
The problem is that the ActionLink has no way to get the value from the input in client side... just the original value.
If you press the Search button, you will see a value posted.
Now, you can use some jQuery to modify a standard ActionLink (not the Ajax.ActionLink):
https://stackoverflow.com/a/1148468/7720
Or... you can transform your Form in order to do a Ajax post instead of a normal one:
https://stackoverflow.com/a/9051612/7720
I did this for a model of mine like so. I ONLY supported the HttpPost method. So add the HttpMethod="POST" to your Ajax.ActionLink
[HttpPost]
public ActionResult Accounts(ParametricAccountsModel model)
{
if (model.Accounts == null)
{
GetAccountsForModel(model);
}
if (model.AccountIds == null)
{
model.AccountIds = new List<int>();
}
return View(model);
}
On the razor view
#Ajax.ActionLink(
"Add Account to Order", "Accounts", "Parametric", null,
new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "...", HttpMethod = "POST" },
new { #id = "AddParametricAccountLink" })
The model has a list of selected account ids. So in javascript, I modified the href of the action link dynamically.
function UpdateParametricAccountAction() {
var originalLink = '/TradeNCashMgmt/Parametric/Accounts';
var append = '';
var numberOfRows = $('#ParametricAccounts').find('.parametric-account- row').size();
for (var i = 0; i < numberOfRows; i++) {
if (i != 0) {
append += '&';
}
else {
append = '?';
}
var idValue = $('#NotionalTransactionsAccountId_' + i).val();
append += 'AccountIds%5B' + i + '%5D=' + idValue;
}
$('#AddParametricAccountLink').attr('href', originalLink + append);
}
Since the model binder looks for parameter names in the query string and form submission, it will pick up values using the href. So I posted a model object using the querystring on my Ajax.ActionLink. Not the cleanest method, but it works.

Asp.NET MVC ajax is loading bad page

I have a layout page inside which i have a table with delete button
when i press a delete button it is showing some thing like .
my ajex option is like.
#{
AjaxOptions xPost = new AjaxOptions();
xPost.HttpMethod = "POST";
xPost.Confirm = "Do you wish to submit this form ?";
xPost.OnBegin = "OnBegin";
xPost.OnComplete = "OnComplete";
xPost.OnFailure = "OnFailure";
xPost.OnSuccess = "OnSuccess";
xPost.LoadingElementDuration = 1000;
xPost.LoadingElementId = "divProgress";
xPost.UpdateTargetId = "divResponse";
xPost.InsertionMode = InsertionMode.Replace;
}
and on delete i am subbmiting the form to a controll like
public ActionResult Delete(int id)
{
ContactPersonManager.Delete(id);
return RedirectToAction("List");
}
As you are using ajax, you could return the URL from your action and have it redirected in javascript:
Controller
public ActionResult Delete(int id)
{
ContactPersonManager.Delete(id);
return Json(new { success = true, redirecturl = Url.Action("List") });
}
Then add something like this to your OnSuccess handler in javascript:
Javascript
function anOnSuccessFunction (data)
{
if (data.success == true)
{
window.location = data.redirecturl;
}
}
Markup
Make sure you point your Ajax options to the javascript function.
xPost.OnSuccess = "anOnSuccessFunction";

Returning Multiple partial views from single Controller action?

I need to update Multiple from an Ajax call , I am confused as in how to return these Multiple views from the Controller Action method.
You can only return one value from a function so you can't return multiple partials from one action method.
If you are trying to return two models to one view, create a view model that contains both of the models that you want to send, and make your view's model the new ViewModel.
E.g.
Your view model would look like:
public class ChartAndListViewModel
{
public List<ChartItem> ChartItems {get; set;};
public List<ListItem> ListItems {get; set;};
}
Then your controller action would be:
public ActionResult ChartList()
{
var model = new ChartAndListViewModel();
model.ChartItems = _db.getChartItems();
model.ListItems = _db.getListItems();
return View(model);
}
And finally your view would be:
#model Application.ViewModels.ChartAndListViewModel
<h2>Blah</h2>
#Html.RenderPartial("ChartPartialName", model.ChartItems);
#Html.RenderPartial("ListPartialName", model.ListItems);
There is a very good example here....
http://rhamesconsulting.com/2014/10/27/mvc-updating-multiple-partial-views-from-a-single-ajax-action/
Create a helper method to package up the partial view...
public static string RenderRazorViewToString(ControllerContext controllerContext,
string viewName, object model)
{
controllerContext.Controller.ViewData.Model = model;
using (var stringWriter = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
var viewContext = new ViewContext(controllerContext, viewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return stringWriter.GetStringBuilder().ToString();
}
}
Create a controller action to bundle the multiple partial views....
[HttpPost]
public JsonResult GetResults(int someExampleInput)
{
MyResultsModel model = CalculateOutputData(someExampleInput);
var totalValuesPartialView = RenderRazorViewToString(this.ControllerContext, "_TotalValues", model.TotalValuesModel);
var summaryValuesPartialView = RenderRazorViewToString(this.ControllerContext, "_SummaryValues", model.SummaryValuesModel);
return Json(new { totalValuesPartialView, summaryValuesPartialView });
}
Each partial view can use its own model if required or can be bundled into the same model as in this example.
Then use an AJAX call to update all the sections in one go:
$('#getResults').on('click', function () {
$.ajax({
type: 'POST',
url: "/MyController/GetResults",
dataType: 'json',
data: {
someExampleInput: 10
},
success: function (result) {
if (result != null) {
$("#totalValuesPartialView").html(result.totalValuesPartialView);
$("#summaryValuesPartialView").html(result.summaryValuesPartialView);
} else {
alert('Error getting data.');
}
},
error: function () {
alert('Error getting data.');
}
});
});
If you want to use this method for a GET request, you need to remove the [HttpPost] decorator and add JsonRequestBehavior.AllowGet to the returned JsonResult:
return Json(new { totalValuesPartialView, summaryValuesPartialView }, JsonRequestBehavior.AllowGet);
Maybe this solution can help you:
http://www.codeproject.com/Tips/712187/Returning-More-Views-in-an-ASP-NET-MVC-Action

Resources