Method does not return view after Ajax - javascript

I have a GetPerson method which returns a People view.
Public ActionResult GetPerson()
{
//code shortened for brevity
return View(people);
}
and here's my view
#model ModelLayer.Models.NotificationModel
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, Kendo.Mvc
#using Kendo.Mvc.UI
#{ ViewData["Title"] = "Index"; }
<div>
//code shortened for brevity
</div>
$("#customSaveButton").on("click", function () {
var model = JSON.parse('#Html.Raw(Json.Serialize(Model?.uploadModels))');
$.ajax({
method: "POST",
url: '#Url.Action("SaveFile", "Upload")',
data: {
model: model,
saveType: saveType
}
})
});
I get the model from the People view and send it to another method SavePeople via an ajax call but my SavePeople method does not want to return a view because of the ajax call and here's my method
public ActionResult SavePeople(List<People> model)
{
//code shortened for brevity
ViewBag.Message = String.Format(cmdMessage);
return View(tModel);
}
What are my options here? Will using a partial view resolve this? Or should I go with something else?

Related

ASP.NET form not submitting

When I click submit, the page is refreshed and looks like everything went through, but is not hitting the ActionResult I am trying to send it to.
I've tried submitting normally and with JavaScript and neither will work.
<form method="post" autocomplete="off" asp-controller="Default" asp-action="Submit">
<button id="SubmitButton" type="submit">Submit</button>
</form>
Controller Method:
namespace (Removed).Controllers
{
public class DefaultController : Controller
{
[HttpPost]
public ActionResult Submit()
{
DBController1 DB1 = new DBController1();
AlertManagement am = new AlertManagement();
am.FirstName = Request.Form["FirstName"];
am.LastName = Request.Form["LastName"];
am.Email = Request.Form["EmailAddress"];
am.Mobile = Request.Form["PhoneNumber"].Replace("(", "").Replace(")", "").Replace(" ", "").Replace("-", "");
am.Affiliation = Request.Form["Affiliation"];
am.StartDate = Convert.ToDateTime(Request.Form["StartDate"]).Date;
am.EndDate = Convert.ToDateTime(Request.Form["EndDate"]).Date;
DB1.AlertManagement.Add(am);
DB1.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Index()
{
return View();
}
}
}
Here is the RouteConfig:
namespace (Removed)
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Index",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Submit",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Submit", id = UrlParameter.Optional }
);
}
}
}
When I click submit, it always goes to ActionResult Index()
Taking a shot in the dark here, but does your controller look like this?
public class DefaultController: Controller
{
[HttpPost] // This attribute states that this action result can only be accessed when using http POST verb.
public IActionResult Submit()
{
return RedirectToAction("index", "home");
}
}
Also, what are you posting? If you have intentionally left out the fields in your example make sure that in your POST method you have this.
<form method="post" autocomplete="off" asp-controller="Default" asp-action="Submit">
<input type="text" name="nameOfElement" id="clientName" />
<button id="SubmitButton" type="submit">Submit</button>
</form>
public class DefaultController: Controller
{
[HttpPost]
public IActionResult Submit([FromForm] string nameOfElement)
{
return RedirectToAction("index", "home");
}
}
try this
<form action="/Default/Submit" method="post">
<input type="submit">
</form>
the ActionMethod you are expecting to be called is of Verb 'GET' while your Form submit method type is 'POST'
add HttpPost attribute it shouls work
[HttpPost]
Public ActionResult Submit()
{
}

Ajax.beginForms MVC Partial View

I am using an ajax.beginform to create a partial view within another view.
I the user enters a correct sn everything works fine.
But if the user enters an invalid number, I want to redirect to the index view.
Now the index page is submitted as a partial view in itself.
How can I avoid that.
Here is a part of my view and 2 simplified actionresults.
#using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST", UpdateTargetId = "form-content", InsertionMode =
InsertionMode.ReplaceWith }))
{
#Html.AntiForgeryToken()
<input type="text" id="sn" name="sn" class="inputsn"
placeholder="Enter your serial number here..." />
<input type="submit" value="Search" class="search btn btn-success btn-lg" />
}
</div>
</div>
<div id="form-content"></div>
my Controller
public ActionResult Index(bool? isValidMachine = null)
{
ViewBag.invalidSerialNumber = isValidMachine;
return View();
}
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if(string.IsNullOrEmpty(sn))
RedirectToAction("Index", new { isValidMachine = false });
QrCreateViewModel qrCreateVM;
using (var machineService = new MachineApiService())
{
var machine = machineService.GetMachineFromSerialNumber(sn);
if (machine == null)
return RedirectToAction("Index", new { isValidMachine = false });
else
qrCreateVM = new QrCreateViewModel(machine, GetBasePath());
}
if (qrCreateVM.IsValid())
{
qrCreateVM.Viewurl = qrCreateVM.QrCreateUrlOrDefaultNull();
return PartialView(qrCreateVM);
}
else
return RedirectToAction("Index", new { isValidMachine = false });
}
Ajax calls do not redirect (the purpose of making them is to stay on the same page).
In your controller method, replace the instances of return RedirectToAction(...) to return a HttpStatusCodeResult indicating an error, which you can then handle in the OnFailure option to redirect to the Index() method.
For example
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if (string.IsNullOrEmpty(sn))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
....
Then in the Ajax.BeginForm()
#using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST",
UpdateTargetId = "form-content",
InsertionMode = InsertionMode.ReplaceWith,
OnFailure = "redirect"
}))
{
....
and add the following script to redirect
function redirect(ajaxContext) {
location.href = '#Url.Action("Index")';
}

Not getting a callback with Ajax.BeginForm asp.net mvc

I am unable to hit the server code using Ajax.BeginForm()
Here is part of my View where I used the Ajax Helper method
#model Ride.MMReports.ViewModels.ManualRecViewModel
.....
var options = new AjaxOptions
{
OnBegin = "OnBeginMethod",
OnFailure = "OnFailureMethod",
OnSuccess = "OnSuccessMethod",
OnComplete = "OnCompleteMethod",
HttpMethod = "Post"
};
using (Ajax.BeginForm("Index", "ManRecReport", options))
{
<button type="submit"
name="action"
value="Export to excel"
id="export-excel"
class="btn btn-primary"
Export to excel
</button>
}
#section scripts
{
#Scripts.Render("~/bundles/report")
#Scripts.Render("~/bundles/jqueryval")
}
My bundle include jquery.unobtrusive-ajax.js and also reports.js where I have all the event methods
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
reports.js bellow. The browser is able to show the alert but last method it calls is OnFailureMethod
var isError = false;
function OnBeginMethod() {
alert("OnBeginMethod");
}
function OnFailureMethod(error) {
isError = true;
alert("OnFailure");
}
function OnSuccessMethod(data) {
alert("OnSuccess");
}
function OnCompleteMethod(data, status) {
if (!isError) {
alert("OnCompleteMethod");
}
}
The problem here is when I click the button, jquery-3.1.1.js is failing
http://localhost:31111/[object%20HTMLButtonElement] 404 (Not Found)
failing at this line
xhr.send( options.hasContent && options.data || null );
My Controller method looks like this:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Index(ManualRecViewModel vm)
{
....
}
Any thoughts what I am doing wrong?

get a view page using jquery in mvc4

Hi I am working with mvc4
I have a razor view page for the action
public ActionResult DeliveryAddress(string userid,int productid)
{
....
return View(m);
}
that contain
<div >DELIVER HERE</div>
when clicking on this i am collecting somedata ifrom this page using jquery,
$(document).ready(function () {
$("#place-order").click(function () {
var userid = $('#selected-userId').html();
var productid = $('#selected-productId').html();
$.get("Products/PlaceOrder/"+ userid, function (data) { });
});
});
and i want to pen another view of action
[HttpGet]
public ActionResult PlaceOrder(int uid)
{
return View();
}
and paste the variable content,
but $.get("Products/PlaceOrder", function (data) { }); is not hitting this action..
please help me.
This is how you need to pass a data to a url in Jquery get method, note the same parameter name is used in the function
$.get('#Url.Action("PlaceOrder","Products")', { uid: userid }, function (data)
{
});
Make sure your URL is correct. Most probably use #Url.Action(). and also pass the parameter using new as shown below.
$.get('#Url.Action("PlaceOrder","Products",new { userid = #userid , productid = #productid })', function (data) {
});
While collecting the data make sure your parameter names are same for both while sending and while receiving.
[HttpGet]
public ActionResult PlaceOrder(int userid, int productid )
{
return View();
}
Just add HTTPGET attribute in your action method as below.
[HttpGet]
public ActionResult PlaceOrder()
{
return View();
}
java script
$("#place-order").click(function () {
var userid = $('#selected-userId').html(); // $('#selected-userId').val();
$.get('#Url.Action("PlaceOrder","Products", new { uid = userid })', function (data) { });
var productid = $('#selected-productId').html();
});
When I want my view code to be fetched like that, or even through the Html.Action() call, I use the PartialView and normally set my Controller Action as:
public ActionResult PlaceOrder(int uid)
{
return PartialView(new TestViewModel() { ID = uid });
}
as an example:
TestViewModel
public class TestViewModel
{
public int ID { get; set; }
}
PlaceOrder.cshtml
#model TestViewModel
<h2>Partial View</h2>
<p>
Partial View paragraph with the id <b>#Model.ID</b>
</p>
Index.html
<hr />
#Html.Action("PartialView", "Home", new { id = 44 })
<hr />
<div class="ap"></div>
<script>
var url = '#Url.Action("PartialView", "Home")';
$.get(url, { id: 54 }, function (data) {
$(".ap").append(data);
});
</script>
result:

Unable to overload submit method of Ajax.BeginForm

I'm trying to submit an ajax form from my razor view, and I want the controller to return a JSON object. When I use ("#form0").submit(alert("hi");); the data goes to the controller and I get an alert. However, when I use ("#form0").submit(function(){alert("hi");}); the data does not get passed, and I do not get an alert. I get the feeling that this is something minor with my syntax that I'm missing. Here's the relevant code:
jquery:
$(function () {
//setting up the schedule modal dialoag.
$("#schedModal").dialog({
buttons: {
Submit:
function () {
$("#form0").ajaxSubmit(function () {
//this is where I want to put the magic, but I need the alert to fire first.
alert("hi");
return false;
});
},
Cancel:
function () {
$(this).dialog("close");
}
},
autoOpen: false,
minHeight: 350,
modal: true,
resizable: false
});
the targeted view:
#model FSDS.DataModels.Schedule
#using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { UpdateTargetId = "partial" }, new {}))
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.ScheduleName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ScheduleName)
#Html.ValidationMessageFor(model => model.ScheduleName)
</div>
#* tons of other labels and editor fields go in here, omitted for brevity. *#
}
The controller, if that matters:
[HttpPost]
public ActionResult scheduleNew(Schedule schedule)
{
if (Request.HttpMethod == "POST")
{
FSDSDBEntities context = new FSDSDBEntities();
if (ModelState.IsValid)
{
context.Schedules.AddObject(schedule);
context.SaveChanges();
}
return Json(schedule);
}
else
{
return PartialView();
}
}
Simply use $('#form0').submit();:
Submit: function () {
$('#form0').submit();
}
Then define an OnSuccess handler in your AjaxForm that will be invoked when the AJAX request succeeds:
#using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { OnSuccess = "success", UpdateTargetId = "partial" }, new {}))
and finally success javascript handler:
function success(data) {
// the form was successfully submitted using an AJAX call.
// here you could test whether the data parameter
// represents a JSON object or a partial view
if (data.ScheduleName) {
// the controller action returned the schedule JSON object
// => act accordingly
} else {
// the controller action returned a partial view
// => act accordingly
}
}

Categories