Return int from MVC Action with Ajax.BeginForm - ajax

Whats the simplest way of just returning an int from an Ajax MVC Action call?
I am currently trying:
public ContentResult Create(MyModel model)
{
return Content("1");
}
using (Ajax.BeginForm("Create",
new AjaxOptions {
OnComplete = "function(data) { alert(data); }"
}))
I get alert [object Object]. How do I get the int value? Or if possible return the int directly instead of having to use a ContentResult?

I would do something like this:
public JsonResult Create(MyModel model)
{
return Json(new { Result = 1 });
}
using (Ajax.BeginForm("Create",
new AjaxOptions {
OnComplete = "function(data) { alert(data.get_response().get_object().Result); }"
}))

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());
}

How to update an MVC partial view with regular 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);
}

HttpPost with AJAX call help needed

what else do i need in my code please, I have this so far:
<script type="text/javascript">
function PostNewsComment(newsId) {
$.ajax({
url: "<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").val(), success: function (data) {
$("#news-comment-content").html(data + $("#news-comment-content").html());
type: 'POST'
}
});
}
$("#textareaforreply").val("");
</script>
and
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(int newsId, string newsComment)
{
if (!String.IsNullOrWhiteSpace(newsComment))
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(newsId, newsComment, currentUser.UserId);
Zinc.DataModels.News.NewsCommentsDataModel model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return null;
}
<div class="actions-right">
<%: Html.Resource(Resources.Global.Button.Reply) %>
</div>
i have no idea how this works, because it is not working in FF???
and the other thing is i must not pass return null i must pass JSON false ???
any help please?
thanks
You should encode your request parameters. Right now you have concatenated them to the request with a strong concatenation which is a wrong approach. There's a property called data that allows you to pass parameters to an AJAX request and leave the proper url encoding to the framework:
function PostNewsComment(newsId) {
$.ajax({
url: '<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>',
type: 'POST',
data: {
newsId: newsId,
newsComment: $('#textareaforreply').val()
},
success: function (data) {
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
});
}
Also you haven't shown where and how you are calling this PostNewsComment function but if this happens on the click of a link or submit button make sure that you have canceled the default action by returning false, just like that:
$('#someLink').click(function() {
PostNewsComment('123');
return false;
});
and the other thing is i must not pass return null i must pass JSON false ???
You could have your controller action return a JsonResult in this case:
return Json(new { success = false });
and then inside your success callback you could test for this condition:
success: function (data) {
if (!data.success) {
// the server returned a Json result indicating a failure
alert('Oops something bad happened on the server');
} else {
// the server returned the view => we can go ahead and update our DOM
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
}
Another thing you should probably be aware of is the presence of dangerous characters such as < or > in the comment text. To allow those characters I would recommend you build a view model and decorate the corresponding property with the [AllowHtml] attribute:
public class NewsViewModel
{
public int NewsId { get; set; }
[AllowHtml]
[Required]
public string NewsComment { get; set; }
}
Now your controller action will obviously take the view model as argument:
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(NewsViewModel viewModel)
{
if (!ModelState.IsValid)
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(viewModel.NewsId, viewModel.NewsComment, currentUser.UserId);
var model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return Json(new { success = false });
}

Ajax.BeginForm that can redirect to a new page

I have an #Ajax.BeginForm for my model which has a boolean value (#Html.CheckBoxFor). If this is checked, I want my HttpPost action to redirect to a new page. Otherwise I want it to just continue being an #Ajax.BeginForm and update part of the page.
Here is my HttpPost action (Note: Checkout is the boolean value in my model)
Controller:
[HttpPost]
public ActionResult UpdateModel(BasketModel model)
{
if (model.Checkout)
{
// I want it to redirect to a new page
return RedirectToAction("Checkout");
}
else
{
return PartialView("_Updated");
}
}
You could use JSON and perform the redirect on the client:
[HttpPost]
public ActionResult UpdateModel(BasketModel model)
{
if (model.Checkout)
{
// return to the client the url to redirect to
return Json(new { url = Url.Action("Checkout") });
}
else
{
return PartialView("_Updated");
}
}
and then:
#using (Ajax.BeginForm("UpdateModel", "MyController", new AjaxOptions { OnSuccess = "onSuccess", UpdateTargetId = "foo" }))
{
...
}
and finally:
var onSuccess = function(result) {
if (result.url) {
// if the server returned a JSON object containing an url
// property we redirect the browser to that url
window.location.href = result.url;
}
}

Resources