How can I get the main view, containing the partial view? - view

I get partial view after form submission (it does not contain the main view). How can I get the main view, containing the partial view?
view:
#using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "result", OnBegin = "onBegin()", OnComplete = "onComplate()" }))
{
<div id="result"></div>
...
controller:
public ActionResult Index()
{
return View(model);
}
[HttpPost]
public PartialViewResult Index(mdl model)
{
...
return PartialView("_part", model);
}

Related

AJAX in MVC does not call junction

index.cshtml
<script type="text/javascript">
function OnSuccessComment(data) {
alert(data.resultMessage);
}
</script>
#using (Ajax.BeginForm(new AjaxOptions
{
Url = Url.Action("AddCommentAjax"),
OnSuccess = "OnSuccessComment",
HttpMethod = "POST"
}))
{
#Html.TextArea("comment")
<input type="submit" value="Добавить комментарий" />
}
HomeController.cs
namespace WebApplication12.Controllers
{
public class HomeController : Controller
{
private static List<string> _comments = new List<string>();
public ActionResult Index()
{
return View(_comments);
}
[HttpPost]
public ActionResult AddComment(string comment)
{
//необходимые действия
return View();
}
[HttpPost]
public ActionResult AddCommentAjax(string comment)
{
//необходимые действия
return Json(new { resultMessage = "Ваш комментарий добавлен успешно!" });
}
}
}
The problem is that function AddCommentAjax does not get called on button click. How to fix that? What is the problem?
#using (Ajax.BeginForm("AddCommentAjax", "Home", new AjaxOptions { OnSuccess = "OnSuccessComment",
HttpMethod = "POST"
}))
Try something like this
Don't forget to include javascript file:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

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.

Return int from MVC Action with Ajax.BeginForm

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

Resources