I'm totally a noob to MVC Framework. And I want to call my Agentcontroller's action method which is in the Controller folder.
I'm trying to call
Controller/Agentcontroller/myactionmethod()
from View Folder
View/Agent/CodeGenerate.cshtml
I think I'm having trouble with the route but I can't find the App_Start folder. This is the script I'm using.
<script type="text/javascript">
function G() {
$.ajax({
type: "post",
url: '/AgentsControllers/',
data: $('form').serialize(),
success: function (response) {
alert("Hi");
}
});
}
</script>
I've also checked this out as well: MVC - calling controller from view
Thanks in advance!
Your Ajax call should be :
<script type="text/javascript">
function G() {
$.ajax({
type: "post",
url: '/AgentsControllers/myactionmethod/',
data: $('form').serialize(),
success: function (response) {
alert("Hi");
}
});
}
</script>
And your Controller Action Method Should be :
[HttpPost]
public ActionResult myactionmethod(YourModelName objYourModelobject)
{
return PartialView("~/Views/Agent/CodeGenerate.cshtml", objYourModelobject);
}
And Your View Should be :
#model Application.Model.YourModel
#using (Html.BeginForm("Agentcontroller", "myactionmethod", FormMethod.Post, new { #class = "example" }))
{
//HTML Helpers
#Html.HiddenFor(model => model.Id, new { #id = "hdnDetailId" })
<button type="submit" class="btn btn-success" id="btnSave"><i class="fa fa-floppy-o"></i> Save</button>
}
Related
I have a button that takes data from a Model and passes it into an Ajax function.
This function should then call a controller, but it doesn't and a breakpoint on a controller is never hit.
The button with parameters taken from Model (both are strings):
<button class="btn btn-primary btn-lg active" onclick="PassHwData(#obj.Name,#obj.HomeWorldBonus)" >Choose #obj.Name</button>
the Ajax function:
<script>
function PassHwData(name, hwBonus)
{
$.ajax({
url: '#Url.Action("Create", "HomeWorld")',
type: "POST",
data: {'name' : name, 'hwBonus' : hwBonus}
datatype: "text",
success: function(name, hwBonus)
{
document.getElementById('success').innerHTML += success {name}{hwBonus};
}
})
}
</script>
<div id=success>
success:
</div>
The Controller (there are other methods but I omitted them here):
using DarkHeresy.Application.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DarkHeresy.Web.Controllers
{
[Authorize]
public class HomeWorldController : Controller
{
private readonly IHomeWorldService _homeWorldService;
public HomeWorldController(IHomeWorldService homeWorldService)
{
_homeWorldService = homeWorldService;
}
[HttpPost]
public async Task<IActionResult> Create(string name, string hwBonus)
{
return View(await _homeWorldService.UpdateCharacterList()); //this will have implementation later
}
}
}
I should also add that I am using Asp.Net Core MVC and going with Clean Architecture and am super new at both of those things.
You can use this alternative way to send the data via AJAX to your Controller method:
HTML:
<button class="btn btn-primary btn-lg active" onclick="PassHwData('#obj.Name','#obj.HomeWorldBonus')" >Choose #obj.Name</button>
AJAX:
<script>
function PassHwData(name, hwBonus)
{
console.log(name);
console.log(hwBonus);
var json = {
name : name,
hwBonus : hwBonus
};
$.ajax({
type: "POST",
url: "#Url.Action("Create", "HomeWorld")",
dataType: "json",
data: {"json": JSON.stringify(json)},
success: function(name, hwBonus)
{
document.getElementById('success').innerHTML += success {name}{hwBonus};
}
})
}
</script>
<div id="success">
success:
</div>
Controller method:
using DarkHeresy.Application.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json; //For .NET CORE
namespace DarkHeresy.Web.Controllers
{
[Authorize]
public class HomeWorldController : Controller
{
private readonly IHomeWorldService _homeWorldService;
public HomeWorldController(IHomeWorldService homeWorldService)
{
_homeWorldService = homeWorldService;
}
[HttpPost]
public async Task<IActionResult> Create(string json)
{
var jsondata = JsonSerializer.Deserialize<dynamic>(json);
//Get your variables here from AJAX call
var name = jsondata["name"];
var hwBonus = jsondata["hwBonus"];
return View(await _homeWorldService.UpdateCharacterList()); //this will have implementation later
}
}
}
change dataType of ajax to 'json'
I have an application that need to post back through Ajax. Getting problem while calling the ActionMethod. below are the code.
Controller :
[HttpGet]
public ActionResult Index()
{
return View();
}
public JsonResult AjaxTest(object name)
{
return Json("Welcome" + name, JsonRequestBehavior.AllowGet);
}
Cstml :
<form name="frmTest" method="POST">
#Html.Label("Your name Please")
#Html.TextBox("username")
<input class="btn btn-success btn-lg btn-block" type="submit" value="Login">
JQuery :
$(function () {
$("form[name='frmTest']").submit(function (e) {
var name = $('#username').val();
$.ajax(
{
type: "POST",
//contentType: "application/json; charset=utf-8",
url: "MyTest/AjaxTest",
dataType: "json",
data: { name:name },
success: function (data, status) {
alert("Pass"+data);
},
error: function () {
alert("Fail");
}
});
});
});
By using the above code break point hit to AjaxTest with the parameter. when I use contentType: "application/json; charset=utf-8", then the page postedback without hitting the break point.
But both cases I got fail alert. unable to find the issue,
I am not sure what you are trying to do but since in one of the comments you stated you will be saving stuff to the database, normally, in ASP MVC it would be done like this.
Create a class for whatever you will be posting using AJAX. For example, in this example, I created a class called Person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Then in your form you can have something like this:
#{
ViewBag.Title = "Test";
}
<form name="frmTest" method="POST">
#Html.Label("Your name Please")
#Html.TextBox("username")
<input class="btn btn-success btn-lg btn-block" type="submit" value="Login">
</form>
<script>
$(function () {
$("form[name='frmTest']").submit(function (e) {
var name = $('#username').val();
$.ajax(
{
type: "POST",
//contentType: "application/json; charset=utf-8",
url: "AjaxTest",
dataType: "json",
data: { "Age": 55, "Name": name },
success: function (data, status) {
alert("Pass" + data);
},
error: function (ex) {
alert("Fail" + ex);
}
});
});
});
</script>
Then have an action which the JSON will be submitted to. For the above, the action will be like this:
public JsonResult AjaxTest(Person person)
{
return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet);
}
ASP MVC will take care of the binding for you. Please also note the url I am posting is "AjaxTest" and it will post to AjaxTest action method of the controller which served the form.
If you have a controller like below, then all of the above will work.
public class AccountController : Controller
{
// This returns the view with the form
public ActionResult Test()
{
return View();
}
public JsonResult AjaxTest(Person person)
{
return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet);
}
}
I'm a beginner & I'm trying to develop a autocomplete search box with ASP.Net MVC 5. I use Northwind Database and Entity Framework 6.
Here is my index.cshtml code
#model IEnumerable<AutoComplete3.Models.Customers>
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("GetCustomers")'
});
});
</script>
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Here is my CustomerController class
public class CustomersController : Controller
{
northwindEntities db = new northwindEntities();
public ActionResult Index()
{
return View(db.Customers);
}
[HttpPost]
public ActionResult Index(string SearchTerm)
{
List<Customers> customers;
if (string.IsNullOrEmpty(SearchTerm))
{
customers = db.Customers.ToList();
}
else
{
customers = db.Customers.Where(c => c.CompanyName.StartsWith(SearchTerm)).ToList();
}
return View(customers);
}
public JsonResult GetCustomers(string term)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
}
This code is working when i am searching records, by entering keyword & clicking submit button. But the GetCustomer method cannot be called by the jquery script. Inspect Elements shows following error.
Uncaught TypeError: $(...).autocomplete is not a function
The text box should be suggest Company Names to the textbox itself. How to correct this.
Thanks.
Javascript
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetCustomers","Home")',
type: "POST",
dataType: "json",
data: { searchTerm: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CompanyName, value: item.CompanyName };
}))
}
})
},
messages: {
noResults: "", results: ""
},
});
})
View
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Controller
Please update your controller with [HttpPost]
[HttpPost]
public JsonResult GetCustomers(string searchTerm)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
I have three partial views on main view
on the first partial view I have search functionality and when user clicks on search I want to refresh results into 3rd partial view.
Controller:
public ActionResult Search()
{
virtualmodel vm = new virtualmodel();
return PartialView(svm);
}
[HttpPost]
public ActionResult Search(ViewModel svm)
{
// Query to retrive the result
// I am not sure what to return from here. Link to another action or just return back to same same partial
}
public ActionResult AnotherPartialPartial()
{
}
In main view
#{Html.RenderAction("Search", "Searchc");
}
How to do it? Do I need ajax?
Using ajax you can call a controller action and return it's response to a particular div.
Empty div:
<div class="row" id="div3">
</div>
Ajax to display html in empty div:
function performSearch(searchCriteria) {
//get information to pass to controller
var searchInformation = JSON.stringify(**your search information**);
$.ajax({
url: '#Url.Action("Search", "ControllerName")',//controller name and action
type: 'POST',
data: { 'svm': searchInformation } //information for search
})
.success(function (result) {
$('#div3').html(result); //write returned partial view to empty div
})
.error(function (xhr, status) {
alert(status);
})
}
jQuery will help you with it!
Try to handle submit button onclick event like this:
$("#yourButtonId").click(function()
{
$.ajax({
type: "POST",
url: "/yourUrl", //in asp.net mvc using ActionResult
data: data,
dataType: 'html',
success: function (result) {
//Your result is here
$("#yourContainerId").html(result);
}
});
});
You can do it with ajax.
First, change your html.beginform to ajax.beginform in your view and add div id into UpdateTargetId that you want to change contents. After updating first partial with ajax.beginform, you can update other partialviews with ajax.beginform's "OnSuccess" function. You have to add update function like that:
#using (Ajax.BeginForm("YourAction", "YourController",
new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" }))
{
/*your code*/
}
<script>
function OnSuccessMethod() {
$("#YouWantToChangeSecondDivID").load('/YourController/YourAction2');
$("#YouWantToChangeThirdDivID").load('/YourController/YourAction3');
};
</script>
Then in your controller, return a partial view to refresh your view part that you entered it's ID in UpdateTargetId value:
public ActionResult YourControllerName(YourModelType model)
{
...//your code
return PartialView("_YourPartialViewName", YourViewModel);
}
Note: Don't forget to add reference to "jquery.unobtrusive-ajax.min.js" in your view while using ajax.
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
#{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('#Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
this is the HTML and JS I have:
</form>
<div class="form-group">
<div class="col-md-4">
<button id="previewButton" class="btn btn-primary">Preview</button>
</div>
</div>
</form>
<script>
$("#previewButton").click(function () {
var request = $.ajax({
url: "/Product/GetRules/",
method: "GET",
dataType: "JSON"
});
request.done(function (data) {
console.log(data);
});
request.fail(function (jqXHR, textStatus) {
console.log(textStatus);
alert("Request failed.");
});
});
</script>
This is the controller code:
public ActionResult GetRules()
{
ProductVM sVM = new ProductVM();
sVM.ProductId = "test123";
sVM.Rules = new List<string>() { ""20/2/15"", "10/2/15" };
return Json(sVM, JsonRequestBehavior.AllowGet);
}
and the Model:
public class ProductVM
{
public string ProductId { get; set; }
public List<string> Rules { get; set; }
}
It hits the controller on debugging and I can see the correct object in VS.
I placed an alert in the .done promise and it works by showing an alert with [object object]
so that means the AJAX call is working fine.
I want to look at the returned JSON so added the log statement but the browser is re-loading the page after the call and there is nothing in the console.
What am I doing wrong here?
Any help is greatly appreciated.
Thanks in advance.
The form is submitting because you need to cancel the default behaviour:
$("#previewButton").click(function (event) {
event.preventDefault();
event.preventDefault()
Description: If this method is called, the default action of the event will not be triggered.
<form> <!-- </form> replaced with <form> -->
<div class="form-group">
<div class="col-md-4">
<button id="previewButton" class="btn btn-primary">Preview</button>
</div>
</div>
</form>
<script>
$("#previewButton").click(function(e) {
e.preventDefault();/* Added prevention */
var request = $.ajax({
url: "/Product/GetRules/",
method: "GET",
dataType: "JSON"
});
request.done(function (data) {
console.log(data);
});
request.fail(function (jqXHR, textStatus) {
console.log(textStatus);
alert("Request failed.");
});
});
</script>