asp.net mvc5 ajax with jquery - asp.net-mvc

I am building a website online store I want when click the add to cart button then number of commodity to be stored in a session with ajax and the message "saved" is displayed But this don’t work and don't display "saved"
View :
<p>
<img src="images/a.jpg">
<input type="text" id="1232542">
<button class="art-button">add to cart</button></p><p id="resolt">
</p>
jQuery :
$('#btntaeid1').click(function () {
var number = $("#1232542").val();
$("#resolt").html('loding...');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Main", "AddToCart")',
data: { 'Number': number },
success: function(aaaa) {
$("#resolt").html(saved);
}
});
});
Session class
public class SessionCommodity
{
private string NumberCommodity;
public SessionCommodity()
{
}
}
AddToCart Action in Main controler
[HttpPost]
public ActionResult AddToCart(int Number)
{
var s = System.Web.HttpContext.Current.Session["cart"] as List<SessionCommodity>;
if (s == null)
{
System.Web.HttpContext.Current.Session["cart"] = s;
}
s.Add(new SessionCommodity {NumberCommodity = Number });
return Json(new {Added = true});
}

You are trying to call the ajax method when the button which has id of "btntaeid1" clicked. But your html content hasnt got that element. Either add the id attribute to the button element or change the click function to be fired when something exist is clicked.
View:
<p>
<img src="images/a.jpg">
<input type="text" id="1232542">
<button id="btntaeid1" class="art-button">add to cart</button></p><p id="resolt">
</p>
or the jquery part according to your post:
$('.art-button').click(function () {
var number = $("#1232542").val();
$("#resolt").html('loding...');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Main", "AddToCart")',
data: { 'Number': number },
success: function(aaaa) {
$("#resolt").html(saved);
}
});
});

Related

How Bind Model data to Telerik Controls?

I am using bellow code to insert the data to db. While Clicking the save button the data should be bind to the model and needs to be posted to controller action . But the data is not bind to the model. What is the issue in the bellow code . Any please help me to solve the below issue.
#(Html.Kendo().TextBoxFor(model => model.Code)
.HtmlAttributes(new { placeholder = "Enter Code", required = "required",
validationmessage="Code is Required" })
)
<input type="button" title="Save" id="btnsave" value="Save" onclick="submit()"/>
<script>
function submit(data) {
debugger;
console.log("Cosoledata "+JSON.stringify(data))
$.ajax({
type: "POST",
url: '#Url.Action("action", "controller")',
data: { data: #Model },
dataType: "json",
success: function (response) {
}
});
}
</script>
data: { data: #Model },
In the JavaScript script, you can directly get the Model data via the #Model.
To send the model data to the controller method, you could create a JavaScript object, then use JQuery to get the related property value (such as Code), then send the object to the controller method.
Please refer the following sample:
View page:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#btnCreate").click(function () {
var review = {}; //create a JavaScript Object.
//user JQuery to get the entered value, and set the property value.
review.ReviewID = $("#ReviewID").val();
review.MovieID = $("#MovieID").val();
review.goreRating = $("#goreRating").val();
review.shockRating = $("#shockRating").val();
review.jumpRating = $("#jumpRating").val();
review.plotRating = $("#plotRating").val();
review.supernaturalRating = $("#supernaturalRating").val();
review.starRating = $("#starRating").val();
//if you want to send multiple objects, you could create an array.
//var reviewlist = [];
//reviewlist.push(review);
$.ajax({
url: "/Home/AddReview",
method: "Post",
data: { "reviewViewModel": review } , // { "reviewViewModel": reviewlist },
success: function (response) {
alert(response);
},
error: function (response) {
console.log("error");
}
})
});
})
</script>
}
Controller method:
[HttpPost]
public IActionResult AddReview(ReviewViewModel reviewViewModel)
{
if (ModelState.IsValid)
{
//do something
}
return View();
}
The result as below:

How to read textContent of a div in the MVC Controller

I am new to ASP.NET MVC. I want to read the textContent of a div and stor that value in a variable of c# server, to do further calculations based on it.
For example:
View side
<div class="target" id="div1">
<div>Start</div>
<div>Process 1</div>
<div>Process 2</div>
<div>Process 3</div>
<div>Stop</div>
</div>
Controller side
public ActionResult Index()
{
var list = /*Read the text content of the div1 */
for(int i=0;i<list.length;i++)
{
switch(list[i])
{
case "Process 1":
//do some tasks
break;
case "Process 2":
//do some task
break;
}
}
return View();
}
Thanks in advance for any help.
After research, I found this as a solution to my requirement:
jQuery.ajax({
type: "POST",
url: "#Url.Action(<actionName>, <controllerName>)",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ <variableToSend> }),
success: function(data) {
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});

jquery autocomplete with ASP.NET MVC

I am trying to get jQuery autocomplete in a textbox. But I don't seem to be able to display the data from my JsonResult in the view, I checked with firebug and verfied that the data is transferred from server, just doesn't disply in the TextBox. I don't get any errors.
Here's my code :
public JsonResult search(string term)
{
// string prefixText =SearchString;
var FamilyLastName = _repository.FamilySearch(term);
var data=FamilyLastName.ToList();
return Json(data);//.Select(x => new { label = x, ID = x }));
}
#using (Html.BeginForm())
{
<label for="SearchString">My Autocomplete:</label>
<input class="form-control" type="text" name="SearchString" id="SearchString" autocomplete="off" />
}
<script type="text/javascript">
$(document).ready(function () {
var param = { "searchstring": $("#SearchString").val() };
$("#SearchString").autocomplete({
autoFocus: true,
source: function (request, response) {
// call your Action
$.ajax({
url:'search?term=' + $("#SearchString").val(),
// data:"{'term':'" +$("#SearchString").val() + "'}",
dataType: 'json',
method: "post",
contentType: "application/json; charset=utf-8",
success: function (data) {
return{
label:data.FamilyLastName
};
},
select:
function (event, ui) {
$('#SearchString').val(ui.item.label);
return false;
},
});
},
minLength: 1,// requ

Ajax call on separate js file

I can use ajax call on *.cshtml file as below.It's working properly.
$.ajax({
url: '#Url.Action("GetAllBooks", "Book")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
But How can I call same method on seperate *.js file ?When I used above code it's not working?
CSHTML (I prefer the tag input):
#* without the attribute 'name' *#
<input type="hidden" value="#Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks" />
#* or *#
<div style="display:none;" data-url="#Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks"></div>
JS:
var url = $('#UrlBookGetAllBooks').val();
//or for tag div
var url = $('#UrlBookGetAllBooks').data('url');
$.ajax({
url: url,
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
HTML - Contains data- attributes
<div id="ExampleDiv"
data-url = "#Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>
HTML - Option 2
<div id="ExampleDiv"
url-Val = "#Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>
JQuery - Contains data- attributes
var Url_Value = $('#ExampleDiv').data('url');
JQuery - Option 2
var Url_Value = $('#ExampleDiv').attr('url-Val');
Ajax Call
$.ajax({
url: Url_Value,
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
For such solution, I recommends you to create a JavascriptController with a "JavascriptActionResult" or a new "JavascriptActionResult" on the BookController along with the view that outputs the desired javascript. That way you can write Javascript dynamically with razor and also have garantee that the Route Pattern behavior of your MVC will be followed. With all that set, the page would be:
<script type="text/javascript" src="#Url.Action("GetAllBooksJS","Book")"></script>
PS: There is not a native JavascriptActionResult in MVC, but you could extend the ActionResult to perform that or simple force a Content-Type in the classic ActionResult function.
Bellow is a working case that Ive made in MVC3.
Controller:
public class BookController : Controller
{
//
// GET: /Book/
public ActionResult Index()
{
return View();
}
public JsonResult GetAllBooks() {
return Json(new[] { new { name = "Book1" }, new { name = "Book2" } });
}
public ActionResult GetAllBooksJS()
{
Response.ContentType = "text/javascript";
return View();
}
}
Index View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="#Url.Content("~/scripts/jquery-1.7.1.min.js")"> </script>
<script type="text/javascript" src="#Url.Action("GetAllBooksJS","Book")"></script>
</head>
<body>
<div>
<button>Get books ajax</button>
</div>
</body>
</html>
GetAllBooksJS View:
#{
Layout = null;
}
$(document).ready(function(){
$('button').on('click',function() {
GetBooksAjax();
});
});
function GetBooksAjax() {
$.ajax({
url: '#Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetAllBooksJS View v2, In this second version the Javascript, as soon as it is loaded by the Index view, will engage the Ajax Call, I guess thats your case:
#{
Layout = null;
}
function GetBooksAjax() {
$.ajax({
url: '#Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetBooksAjax();

How do I get all values of checkbox those are checked using ajax/jQuery in asp.net mvc

Ajax post:
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
// var vals = [];
// $('input:checkbox[name=Blanks]:checked').each(function () {
// vals.push($(this).val());
// });
// alert(vals);
//
var checkboxData = $(':checked').val();
$.ajax({
// Check the value.
type: 'POST',
url: '/Home/Extract',
data: { 'name': checkboxData },
// contentType: 'application/json; charset=utf-8', // No need to define contentType
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
});
Controller method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Extract(string[] name)
{
}
My problem is that I am getting null values in my string[] name when I use array and single checkBox values when I use other case. Any suggestions or ideas as to why the post looks good?
View:
<input type="button" id="btn" value="Extract" style="float:right "/>
#foreach (var m in (List<string>)ViewData["list"])
{
<ul>
<li>
<input type="checkbox" class="myCheckbox" name="Blanks" id="chk" value="#m"/>
<img src="#m" alt=""/>
First start by fixing your markup and remove the id="chk" from your checkboxes because you cannot have 2 elements with the same id.
Alright, and then simply generate a javascript array containing the values of the selected checkboxes and POST this array to the server:
$('#btn').click(function () {
var values = $('input[type="checkbox"].myCheckbox:checked').map(function() {
return $(this).val();
}).toArray();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ name: values }),
contentType: 'application/json',
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
return false;
});
And your controller action signature might look like this:
[HttpPost]
public ActionResult Extract(string[] name)
{
...
}
But all this would have been completely unnecessary if you had used a view model and the strongly typed Html.CheckBoxFor helper.

Resources