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>
Related
I want to pass selected Drop down list value to Ajax Action Link which is I am using in Controller. Every time When I will change drop down list value. I want that respective value pass to the action link.
What I need to write here in Ajax Action Link ????
Drop Down List
<div class="form-group">
#Html.DropDownListFor(model => model.ComponentId, ((List<string>)ViewBag.Cdll).Select(model => new SelectListItem { Text = model, Value = model }), " -----Select Id----- ", new { onchange = "Action(this.value);", #class = "form-control" })
</div>
Ajax Action Link
<div data-toggle="collapse">
#Ajax.ActionLink("Accessory List", "_AccessoryList", new { ComponentId = ???? }, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divacc",
InsertionMode = InsertionMode.Replace
})
</div>
Controller
public PartialViewResult _AccessoryList(string ComponentId)
{
List<ComponentModule> li = new List<ComponentModule>();
// Code
return PartialView("_AccessoryList", li);
}
Here is a new post. I do dropdowns a little different than you, so I am showing you how I do it. When you ask what to pass, I am showing you how to pass the dropdown for 'component' being passed. I also show how to pass from ajax back to the page.
Controller/Model:
//You can put this in a model folder
public class ViewModel
{
public ViewModel()
{
ComponentList = new List<SelectListItem>();
SelectListItem sli = new SelectListItem { Text = "component1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "component2", Value = "2" };
ComponentList.Add(sli);
ComponentList.Add(sli2);
}
public List<SelectListItem> ComponentList { get; set; }
public int ComponentId { get; set; }
}
public class PassDDLView
{
public string ddlValue { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostDDL(PassDDLView passDDLView)
{
//put a breakpoint here to see the ddl value in passDDLView
ViewModel vm = new ViewModel();
return Json(new
{
Component = "AComponent"
}
, #"application/json");
}
public ActionResult IndexValid8()
{
ViewModel vm = new ViewModel();
return View(vm);
}
View:
#model Testy20161006.Controllers.ViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid8</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function () {
var PassDDLView = { ddlValue: $("#passThis").val() };
$.ajax({
url: '#Url.Action("PostDDL")',
type: 'POST',
data: PassDDLView,
success: function (result) {
alert(result.Component);
},
error: function (result) {
alert('Error');
}
});
})
})
</script>
</head>
<body>
<div class="form-group">
#Html.DropDownListFor(m => m.ComponentId,
new SelectList(Model.ComponentList, "Value", "Text"), new { id = "passThis" })
<input type="button" id="btnClick" value="submitToAjax" />
</div>
</body>
</html>
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.
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);
}
I'm using WebGrid and I need to switch between pages with Ajax.
Index Code
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
#using (Ajax.BeginForm("GetGrid", new AjaxOptions() { UpdateTargetId = "Res" }))
{
<input type="text" />
<input type="submit" value="start" />
<div id="Res">
</div>
}
Result partial view
#model IEnumerable<MvcApplication1.Controllers.Model>
<div id="grid2">
#{
var grid = new WebGrid(source:Model,rowsPerPage:6,ajaxUpdateContainerId: "grid2");
#grid.GetHtml(htmlAttributes: new { id = "grid2" },
columns: grid.Columns(
grid.Column("Someting")
));
}
</div>
Controller Code
public class ABCController : Controller
{
//
// GET: /ABC/
public ActionResult Index()
{
return View();
}
public static List<Model> mo = new List<Model>();
[HttpPost]
public ActionResult GetGrid()
{
for (int i = 0; i < 1000; i++)
{
mo.Add(new Model() { Someting = i.ToString() });
}
return PartialView("Result", mo);
}
}
public class Model
{
public string Someting { get; set; }
}
This work for first page but nothing happens for other pages.
After some hours i could not find some thing that help me.i noticed to html code of my page links.
page link
2
so i finally got how it's work.i add an ActioResult to my controller like this:
[HttpGet]
public ActionResult GetGrid(int page)
{
return PartialView("Result",mo);
}
and worked.i hope this be helpfull for some one
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); }"
}))