I have the following problem (I spend many hours looking for a solution).
The ‘Create’ button has a click event which calls the ‘Test’ action on the ‘Home’ controller.
All works fine.
When I hit the ‘Save’ button, to submit the form, that works fine to.
But after I have submitted the form, my ‘Create’ button stops working. The ‘Create’ button does have the click event, but the ‘Test’ action is unreachable?
index.cshtml
<script type="text/javascript">
$(document).ready(function () {
$("#create").click(function () {
$.ajax({
type: "POST",
traditional: true,
url: 'Home/Test',
dataType: "html",
success: function (data) {
alert('Succes!')
},
error: function () {
alert('A problem ocurred!!');
}
});
});
});
</script>
<input id="create" type="button" value="Create" />
#using (Html.BeginForm("SaveForm", "Home"))
{
<input type="submit" value="Save" />
}
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult Test()
{
return Content("Test result");
}
public ActionResult SaveForm()
{
return View("Index");
}
public ActionResult About()
{
return View();
}
}
All of your actions are GET only. Either add [HttpPost] (POST only) or [AcceptVerbs(HttpVerbs.Post, HttpVerbs.Get)] (GET or POST) attributes to your POST actions.
[HttpPost]
public ActionResult Test()
{
return Content("Test result");
}
[HttpPost]
public ActionResult SaveForm()
{
return View("Index");
}
Theres 2 problems:
1) you dont have [HttpPost] above your methods
2) You are not sending any data to your controller
add an id to your form by using an anonymous class:
#using (Html.BeginForm("SaveForm", "Home", new {id = "testform"}))
then rewrite the ajax request:
<script type="text/javascript">
$(document).ready(function () {
$("#create").click(function () {
$.ajax({
type: "POST",
data: $("#testform").serialize();
url: 'Home/Test',
dataType: "html",
success: function (data) {
alert('Succes!')
},
error: function () {
alert('A problem ocurred!!');
}
});
});
});
</script>
Let me know if it works :)
To create an entity, you have to submit your data to server, either by post back or ajax as in your case. Now there are some contradictions in your code :)
1. Why are you calling one action as form action and another through
ajax? Because since your button will post back, your ajax call won't
fire the success and error handlers. To solve this either use <button> or
$("#create").click(function (e) { e.preventDefault();//Some code});
2. If you want to use ajax, write it like this. Also write [HttpPost] on
your action. This indicates that this action can be called by post requests.
This is a required step, whether or not you are using ajax.
I hope this solved your problem.
Eventually I used Ajax.BeginForm instead of Html.BeginForm, added the [HttpPost] attributes to my actions and I used the RedirectToAction("Index") instead of PartialView. That solved my problem. Thanks again for your tips!
Related
I'm using 2019 ASP.NET MVC with jquery 3.4.1. I'm trying to get the error message when I make a jquery ajax post. To simulate an error I mispelled the method in the controller being called by ajax. The best I could do was to display an alert box with some HTML code. It looks like the title tag contains the correct error message: "The resource cannot be found." But it's nested inside of a bunch of html code.
Is there a way to get that error message out of that html code and into a string?
Edit: I figured it out. I just added a span tag and set the html property of it.
Controller
using System.Web.Mvc;
namespace Test
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
//view
return View();
}
[HttpPost]
public ActionResult DoSomething1111111111()
{
return Json("hello");
}
}
}
View
#{
Layout = null;
}
<input type="button" id="test-button" value="test" />
<span id="message"></span>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script>
//test-button click event
$(document).on("click", "#test-button", function () {
//post
$.ajax({
url: "/Home/DoSomething",
type: "POST",
success: function (res) {
alert("success");
},
error: function (res) {
$("#message").html(res.responseText);
}
});
});
</script>
am new to ASP.net. Am trying to have a simple page view that has a button and when clicked, this would call a method that is in a controller, to then do more code and computation with c#.
I read posts and tried this but the method does not seem to be called, the debugger never stops in the Controler ClickButton1 method.
My VIEW code
<div>
<input id="Button1" type="button" value="Button 1" onclick="ClickButton1()" />
<input id="Button2" type="button" value="Button 2" onclick="location.href='#Url.Action("Options", "Home")'" />
</div>
<div>
<canvas id="mapCanvas" width="500" height="150" style="border:1px solid #000000;"></canvas>
</div>
<script>
function ClickButton1() {
$.ajax({
type: "POST",
url: '#Url.Action("ClickButton1", "Definition")',
async: true,
success: function (msg) {
ServiceSucceeded(msg);
},
error: function () {
return "error";
}
});
}
</script>
My CONTROLLER
namespace Traveler.Controllers
{
public class DefinitionController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
// Action click on Button 1
public void ClickButton1()
{
Console.WriteLine("Button 1 Clicked");
}
}
}
Change the input type to button from submit to avoid multiple submit.
Mark you Controllers method as [HttpPost] and try again.
If you are wondering why should you do that, read this:
The [HttpPost] attribute tells the routing engine to send any POST requests to that action method to the one method over the other. This is a type of overloading.
If you are wondering how to mark you Method as a [HttpPost] method, look at this:
[HttpPost]
public void ClickButton1()
{
Console.WriteLine("Button 1 Clicked");
}
I hope this will help you :)
I am using ASP.net MVC with the razor engine.
I have a page with a button, when the button is clicked i call an ActionResult in my controller using Ajax. The Ajax call:
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
//alert("yay");
}
});
My ActionResult method is hit fine, however it does not load the view speified.
The code:
public ActionResult Review()
{
return View();
}
The current view is Index.cshtml when Review() is hit i would like Review.cshtml to be rendered on screen. (It should be rendered as a full view, not as partial view inside Index.cshtml)
I have tried - return View("Review"); return View("Review.cshtml"); return View("..\Views\Home\Review.cshtml);
I can't use - tml.BeginForm("Action", "Controller", FormMethod.Post); (see my other question MVC submit button not firing)
Write the response directly to the screen
success: function (data) {
document.write(data) }
After ajax, you should render a partial view to add returning result to main view(index).
Index.cshtml
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
$("#container").html(data);
//alert("yay");
}
...
<div id="container"></div>
Controller
public ActionResult Review()
{
return PartialView();
}
If you want to redirect after ajax you can use something like following:
Index.cshtml
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
window.location.href = data.url;
}
...
Controller
public ActionResult Review()
{
return Json(new { url = "some url" }, JsonRequestBehavior.AllowGet);
}
I'm using ASP.NET MVC and my model has a list as part of it. I want to pass that list to a javascript function and inside this function I turn around and want to pass it back to a controller.
Currently I have:
#Html.ActionLink("Edit", "Edit", "Data", new { onclick = string.Format("EditRecord({0});", Model.Types) })
Model.Types is defined as List
My javascript EditRecord is defined as:
function EditRecord(types)
{
$.post("/Data/Edit/" { myTypes: types });
}
My controller is define as:
[HttpPost]
public ActionResult Edit(string[] myTypes)
{
return View();
}
When I run this I get page can't be found. If I switch this from the list to just a normal data type like an int or string then it all works, so something with the fact that it's an array is throwing this off. Any ideas?
Here goes my solution, Lets say you have a model holding List property in following way -
public class MyModel
{
public List<string> Types { get; set; }
}
This model will be constructed in the following controller action and will be returned to the View -
public ActionResult Index()
{
MyModel model = new MyModel();
model.Types = new List<string>();
model.Types.Add("Admin");
model.Types.Add("User");
model.Types.Add("SuperAdmin");
return View(model);
}
And the View has following Html -
#model Rami.Vemula.Dev.Mvc.Controllers.MyModel
#{
ViewBag.Title = "Home Page";
}
<div class="row">
Click me
</div>
Now the JQuery part which will hold the logic to send the List to the controller action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.Types = #Html.Raw(Json.Encode(Model.Types));
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {
alert(data);
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
Then on clicking the button, it will hit the following controller -
public JsonResult GetJson(List<string> Types)
{
return Json(Types, JsonRequestBehavior.AllowGet);
}
When you click the button, and put a breakpoint to check the values -
By this your controller is returning blank view. Make sure that your view is created (right click-go to view). And if you want to return it it should be something like this:
rerurn View(myTypes);
But make sure that myTypes view is set up to accept string[].
if you want to pass your list to client consider ajax call that will send json object array and adjust your backend to accept it.
I've checked this question and it solved my initial problems. But I don't want the partial view to be rendered only when the user clicks a link, I want to render partial views when the page is loaded and, possibly, show a progress indicator while the partial view is being loaded.
How to achieve that?
Thank you very much for reading this.
If you want to load the page and then load the partial view via ajax you could create an ActionMethod that does something like:
public ActionResult Create()
{
var model = new MyModel();
if (Request.IsAjaxRequest())
{
return PartialView( "_Partial", model.PartialModel );
}
else
{
return View( model );
}
}
and then in your page do something like:
$(function(){
$(document).ajaxStart(function () {
//show a progress modal of your choosing
showProgressModal('loading');
});
$(document).ajaxStop(function () {
//hide it
hideProgressModal();
});
$.ajax({
url: '/controller/create',
dataType: 'html',
success: function(data) {
$('#myPartialContainer').html(data);
}
});
});
Controller
public ActionResult GetModule(string partialName){
return PartialView("~/Views/Shared/"+partialName);
}
on the Default Page (using jquery ajax operation)
<div id='mod1'>Loading...</div>
<script type="text/javascript">
$("#mod1").load("/ControllerName/GetModule?partialName=test1");
</script>
You can render it in the initial page by writing #Html.Partial(...).