I have asp.net mvc 5 application but I can't get this fairly simple script to work. I am new to this MVC (I am WebForms guy).
Basically jQuery is not attaching .click() event to the button to post data to the underlying controller.
Can somebody pinpoint what I am doing wrong?
The View (HelloWorld/Index.cshtml):
#model HelloWorld.Models.HelloWorldModel
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
</head>
<body>
<div>
#using (Html.BeginForm("Welcome","HelloWorld",FormMethod.Post, new {id = "myhelloform"})){
<span>Name:</span>
#Html.TextBoxFor(model=> model.Name)
<button id="btnPost" type="button">Post</button>
}
</div>
<script>
var testform = function () {
var init = function () {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
};
var submitForm = function () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
}
});
};
return {
Init: init
};
};
</script>
</body>
</html>
</html>
The Controller (Controllers/HelloWorldController.cs):
using System.Web.Mvc;
namespace HelloWorld.Controllers
{
public class HelloWorldController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Welcome()
{
return Json("test");
}
}
}
The Model (Models/HelloWorldModel.cs)
namespace HelloWorld.Models
{
public class HelloWorldModel
{
public string Name { get; set; }
}
}
Delete the variables testform and init and it works (Also need to use $( document ).ready as #Tbseven mentions):
$( document ).ready(function() {
$("#btnPost").on("click", function ()
{
alert("anybody there??");
});
});
Fiddle: https://dotnetfiddle.net/HCdFXM
You have to place your jquery code inside next function:
$( document ).ready(function() {
// Here
});
$( document ).ready(function() {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
function submitForm () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
});
};
});
You can use input instead of button and there is no need to add click event for that.
<input type="submit" id="btnPost" />
Related
I'm using .net core 3.1 razor pages. I have a page with a property. I'm using a jQuery ajax call in my page. Sometimes though my field was filled, but the property got null in my PostAsync method. After spending much time, I found that MyProperty was null (not bound) when I called my $.ajax function in the page before submitting it! Is it a bug in .net core or have I forgotten some settings?
MyPage.chtml:
...
<form method="post">
My Property: <input asp-for="MyProperty" /><br />
<button id="doAction" type="button">Do some action in server</button><br />
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#doAction').click(function(){
$.ajax(
'/api/myaction/doSomeAction/2',
{
type: 'POST',
success: function() { alert('Some action done successfully.'); }
}
});
});
</script>
...
MyPage.chtml.cs:
[BoundProperty]
public string MyProperty { get; set; }
...
public async Task<IActionResult> OnPostAsync()
{
var temp = MyProperty;
...
}
MyAction controller class:
[Route( "api/[controller]" )]
[ApiController]
public class MyActionController : Controller
{
[HttpPost( "doSomeAction/{code?}" )]
public async Task<dynamic> PostAsync( int code )
{
// do some actions...
}
}
Startup.cs:
public void Configure( IApplicationBuilder app , IWebHostEnvironment env )
{
...
app.UseEndpoints( endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute( "default", "{controller}/{action}/{id?}" );
} );
...
}
Scenarios:
Fill MyProperty with "MyValue" and submit form => MyProperty == "MyValue" (OK).
Fill MyProperty with "MyValue"; click doAction button; then submit form => MyProperty == null (binding property failed!)
I don't know exactly where your problem is, but this kind of error will not occur under normal circumstances. You can see my working example below.
Index.chtml:
#page
#model xxxxx.IndexModel
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#Html.AntiForgeryToken()
#{
Layout = "_Layout";
}
<form method="post">
My Property: <input asp-for="MyProperty" /><br />
<button id="doAction" type="button">Do some action in server</button><br />
<button type="submit">Submit</button>
</form>
#section scripts{
<script>
$(document).ready(function () {
$('#doAction').click(function () {
$.ajax(
{
url: '/api/myaction/doSomeAction/2',
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () { alert('Some action done successfully.'); }
})
});
});
</script>
}
In your startup,add:
//...
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Index.chtml.cs:
[BindProperty]
public string MyProperty { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
//...
return Page();
}
MyAction controller class:
[Route("api/[controller]")]
[ApiController]
public class MyActionController : ControllerBase
{
[HttpPost("doSomeAction/{code?}")]
public async Task<dynamic> PostAsync(int code)
{
return "Ok";
}
}
Test Result:
you suppose to be sending data into your ajax post call,
<script>
$(document).ready(function() {
<script>
$(document).ready(function() {
$('#doAction').click(function(){
$.ajax(
'/api/myaction/doSomeAction/2',
{
type: 'POST',
data:$(form).serializeArray();
success: function() { alert('Some action done successfully.'); }
}
});
});
</script>
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 created a API application where I can perform the crud operations. However, I am unable to display all the models in my cshtml.
I have created my API controller, which has the getAllUsers methods and in my home controller, I just call the Index View. In my view, I have a script which calls the getAllUsers methods. Below is my code:
API controller:
namespace WebApiQues.Controllers
{
public class UserController : ApiController
{
private WebApiQuesEntities db = new WebApiQuesEntities();
//Get all users
public IEnumerable<User> GetAllUsers()
{
var UserList = from s in db.Users
orderby s.Id
select s;
return UserList;
}
}
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public UserController userController = new UserController();
public ActionResult Index()
{
//var UserList = userController.GetAllUsers();
//ViewBag.UserList = UserList;
return View();
}
}
Index.cshtml:
#{
ViewBag.Title = "Index";
}
#model IEnumerable<WebApiQues.Models.User>
<div>
<div>
<h2>All Products</h2>
<ul id="products" />
</div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var uri = 'api/user/getallusers';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (data) {
// Add a list item for the product.
$('<li>').appendTo($('#products'));
});
});
});
</script>
I believe the problem comes from the script in cshtml but I can't find where I am doing it wrong. Any idea?
EDITED:
If I add a console.log(data), I can see that data has the list of users.
try this:
add your jquery script to the scripts section:
#section scripts
{
<script type="text/javascript">
$(function() {
var uri = 'api/user/getallusers';
$.getJSON(uri, function(data) {
$.each(data, function(index, v) {
$('#products').append('<li>'+v.PropertyName+'</li>');
//Change property name to the property of your object
});
});
});
</script>
}
$.each expects two arguments in the callback function: the index of your array and the actual data object itself:
callback Type: Function( Integer indexInArray, Object value ) The
function that will be executed on every object.
http://api.jquery.com/jquery.each/
Assuming User has 'Name' property, try this code
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (data) {
// Add a list item for the product.
$('#products').append('<li>'+data.Name+'</li>');
});
});
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>
I was working to use Kendo Grid in asp.net mvc4.Here is the code written in contrller and view.But i am not getting the Kendo Grid in output.Can anyone help me with this?
I have used ADO.NET entity model to form class called Contacts to connect to the database
and in the controller i have converted the data coming from Contacts class to json.
Controller:
public class HomeController : Controller
{
public PersonaEntities db = new PersonaEntities();
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[HttpGet]
public JsonResult Getjsondata()
{
ViewBag.Title = "Hello World";
JsonResult jsonResult = new JsonResult();
var Contacts = db.Contacts.ToList();
jsonResult.Data = Contacts;
return Json(jsonResult,JsonRequestBehavior.AllowGet);
}
Then i have tried in the view to display kendo grid by giving its datasource as controller action method.But I am not getting the output as kendo grid.
View:
#{
ViewBag.Title = "Getjsondata";
}
<h2>Getjsondata</h2>
<link href="~/Content/kendo/2014.2.716/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/2014.2.716/angular.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/jquery.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/kendo.all.min.js"></script>
<script>
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: { read: { url: "Home/Getjsondata", dataType: "json" } },
schema: {
data: function (data) {
return data;
}
}
})
$("#Grid").kendoGrid({
dataSource: dataSource,
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The Json method encapsulated the data into a JsonResult already. Your reposonse is double-wrapped. Pass the data directly into the Json method.
You'll need two actions, one for the static view and one for the JsonResult:
public class HomeController : Controller
{
public ActionResult GridView()
{
return this.View();
}
public JsonResult Getjsondata()
{
var Contacts = db.Contacts.ToList();
return Json(Contacts, JsonRequestBehavior.AllowGet);
}
}
For the view, you need a GridView.cshtml:
#* css and js imports omitted *#
<script>
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: '#Url.Action("Getjsondata")',
type: 'GET', // should be POST, though
}
},
schema: {
type: "json",
model: {
id: "id",
fields: {
'id' : { type: 'number', editable: false},
'fname': { type: 'string' },
'lname': { type: 'string' },
'phone': { type: 'string' }
}
}
}
},
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The url of the page is ~/Home/GridView. When you open the page, the controller only returns the static page GridView.cshtml. Once the page is loaded on the client side (your browser), the JavaScript code will run and make an AJAX request to the ~/Home/Getjsondata action to load the data for the kendo grid.
I found out that i was loading the script jquery.js manually which i think gets loaded by default in browser.Also i found that scripts and css files need to be mentioned only in shared layout file and not necessary to mention it in view.
jquery asp.net-mvc