I have a table that's populated by JSON data. In the last column you can open up a modal that corresponds to each row and you can add a comment in an input box---doing so will update that modal. In other words, table rows that have no comments have an empty modal and rows with at least one comment should appear in the modal that they correspond with.
In my backend manager (SQL Server Management Studio) I can see that the comments are showing up there, but they're not appearing in the modals.
I can't tell if the problem is coming from the JavaScript side (the view) or from the model, or from elsewhere.
The addition of the DocBudgetId is relatively new. Before that, the review/comment data was tied to the DocNumber and the info was appearing in the modals. I suspect that I have to make an adjustment/change to the DocBudgetId but I'm not sure how.
Modal screenshot: https://i.stack.imgur.com/Vqd4o.png The DocNumber appears on the top left. Comments have been made to the row that this modal belongs to but they're not appearing in the modal table.
Model:
public class ReviewRow
{
public Guid DocBudgetId { get; set; }
public string DocNumber { get; set; }
public string ReviewBy { get; set; }
public string ReviewOn { get; set; }
public string ReviewComment { get; set; }
}
View:
<div class="modal-body">
<div id="review"></div>
<table>
<tr>
<td>
#Html.LabelFor(x => Model.ReviewComment)<br />
#Html.TextAreaFor(x => x.ReviewComment, new { style = "width: 200px; " })<br />
#Html.HiddenFor(x => x.DocUnderReview, new { id = "txtDocUnderReview" })
<input type="submit" value="#BB360.Models.BudgetReportingViewModel.Buttons.Review" name="#Html.NameFor(x => x.SubmitButton)" id="SubmitButton" class="btn btn-secondary" />
</td>
</tr>
</table>
// --- other code --- //
function ShowReviewModal(DocBudgetId, DocNumber) {
$("#txtDocUnderReview").val(DocNumber);
console.log(DocNumber)
$.ajax({
type: "POST",
url: "/Doc/GetDocUnderReviewDetails",
data: "docNumber=" + DocNumber + "&docBudgetId=" + DocBudgetId,
timeout: 5000,
success: function(data) {
console.log(data); // ------------- empty array
// write out the modal table
var tBody = $("#tblExpenseDeductionDetails tbody");
tBody.empty();
s = "";
for (x = 0; x < data.length; x++) {
let ReviewBy = data[x].ReviewBy,
ReviewOn = data[x].ReviewOn,
ReviewComment = data[x].ReviewComment;
s = s + "<tr>";
s = s + "<td>" + ReviewBy + "</td>";
s = s + "<td>" + ReviewOn + "</td>";
s = s + "<td title='" + ReviewComment.replace(/'/g, '') + "' style='max-width:550px;word-wrap: break-word;'>" + stringTruncate(ReviewComment, 65) + "</td>";
s = s + "</tr>";
}
$("#modalDocName").text(DocNumber);
tBody[0].innerHTML = s;
$("#ReviewModal").modal();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
$("#ReviewModal").modal();
}
Controller
public ActionResult BudgetReporting(BudgetReportingViewModel model)
{
Common.GetDbExecutor().QueryNonQuery(Sql.InsertDocUnderReview, new {
model.DocBudgetId,
DocNumber = model.DocUnderReview, // D is uppercase
ReviewBy = Common.GetUserName(),
ReviewComment = model.ReviewComment,
}, 30).ToString();
PopulateBudgetReportingDetail(model);
return View(model);
}
public ActionResult GetDocUnderReviewDetails(Guid docBudgetId) // camelCase //
{
var data = Common.GetKKDbExecutor().Query<BudgetReportingViewModel.ReviewRow>(Sql.GetDocUnderReviewDetails, new {
docBudgetId
}).ToList();
return Json(data);
}
Sql file
namespace BB360
{
public partial class Sql
{
public const string GetDocUnderReviewDetails = #"
select
DocBudgetId,
DocNumber,
ReviewBy,
convert(varchar, ReviewOn, 101) as ReviewOn,
isnull(ReviewComment, '') as ReviewComment
from DocBudgetReview
where DocBudgetId = #DocBudgetId
order by ReviewOn desc
";
}
}
The issue here is your "GetDocUnderReviewDetails" action accepts GET request and you're sending a post request to it. You just need to change the ajax request type to GET.
type: "GET",
url: "/Doc/GetDocUnderReviewDetails",
Another thing i noticed is that, you're sending the docNumber also in the request which your action doesn't require. Even though that won't cause any issue but you don't need to send that in ajax
Update: I did some tinkering and got the table data to show.
In the stored procedure (GetDocUnderReviewDetails.cs) I commented out the line where DocBudgetId = #DocBudgetId and added where DocNumber = #DocNumber. I noticed that if I just commented out where DBI = then it showed all of the comments made for every modal, which was an issue I was dealing with earlier.
So now, my stored procedure looks like this:
namespace BB360
{
public partial class Sql
{
public const string GetDocUnderReviewDetails = #"
select
DocBudgetId,
DocNumber,
ReviewBy,
convert(varchar, ReviewOn, 101) as ReviewOn,
isnull(ReviewComment, '') as ReviewComment
from DocBudgetReview
--where DocBudgetId = #DocBudgetId
where DocNumber = #DocNumber
order by ReviewOn desc
";
}
}
I also added string docNumber to the Controller:
public ActionResult GetDocUnderReviewDetails(Guid docBudgetId, string docNumber)
{
var data = Common.GetBBDbExecutor().Query<BudgetReportingViewModel.ReviewRow>(Sql.GetDocUnderReviewDetails, new {
docBudgetId,
docNumber
}).ToList();
return Json(data);
}
Related
Guys how can I send the jsPDF file to the controller while also including the model. I believe I have to change the ajax data: piece, This however is eluding me. Any help would be appreciated.
Model:
public class PartialReportModel
{
public List<ShiftReportDetail> ReportDetails { get; set; }
public ShiftReport Report { get; set; }
public byte[] testingImg { get; set; }
public IFormFile pdf { get; set; }
public List<UserListsForSignatures> ListOfNames { get; set; }
public List<ProductCodes> ProductsList { get; set; }
public List<EquipList> Equipment { get; set; }
public List<CodeTable> CodeList { get; set; }
}
Controller:
[HttpPost]
public async Task<IActionResult> EditReport(PartialReportModel model,IFormFile Test)
{
// do something else here with pdf and model
return Json(1);
}
JS:
$(document).on("click", "#SubmitReportEdits", function () {
var pdf;
html2canvas(document.querySelector("#mod1")).then(canvas => {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm', 'a4', true);
var width = doc.internal.pageSize.width;
var height = doc.internal.pageSize.height;
doc.addImage(imgData, 'PNG', 10, 10, width - 20, height - 10);
pdf = doc.output('blob');
//doc.save('test.pdf');
});
// ajax the thing
$.ajax({
type: "POST",
url: $("#EditReportForm").attr("action"),
data: $("#EditReportForm").serialize() + "&Test="+pdf,
success: function () {
// close the modal
// reload the table
$('#ReviewReport').modal('toggle');
$('#NotificationDiv').append( // change
"<div class='alert alert-success alert-dismissible fade show' role='alert'>
" + "Report has been edited. Thank you." +
"<button type='button' class='close' data-dismiss='alert' aria-
label='Close'>" + "<span aria-hidden='true'>×</span>" + "</button>" + "
</div>"
);
}
});
});
Currently I can see my model stuff but the pdf side is null.
Because we all have deadlines :/, I am going to use this method to work this for now until a better answer comes along.
First is to convert the file to a base64 string, Then set that to a value inside the form. Have a hidden input to receive the value. This case string pdf. Then pass it along the ajax. We now see the value in the controller side. Also have to use jpeg as PNG was too large a file and was getting 413 server errors. Code_debt++
model:
public string pdf { get; set; }
HTML5:
<input asp-for="pdf" hidden/>
Javascript:
$(document).on("click", "#SubmitReportEdits", function () {
html2canvas(document.querySelector("#mod1")).then(canvas => {
var imgData = canvas.toDataURL(
'image/jpeg');
var doc = new jsPDF('p', 'mm', 'a4', true);
var width = doc.internal.pageSize.width;
var height = doc.internal.pageSize.height;
doc.addImage(imgData, 'jpeg', 10, 10, width - 20, height - 10);
var pdf = doc.output('datauristring').slice(28); // wipe first28chars
//saving the base64
$('#pdf').val((pdf));
// ajax the thing
$.ajax({
type: "POST",
url: $("#EditReportForm").attr("action"),
data: $("#EditReportForm").serialize(),
success: function () {
// close the modal
// reload the table
$('#ReviewReport').modal('toggle');
$('#NotificationDiv').append( // change
"<div class='alert alert-success alert-dismissible fade show' role='alert'> " + "Report has been edited. Thank you." +
"<button type='button' class='close' data-dismiss='alert' aria-label='Close'>" + "<span aria-hidden='true'>×</span>" + "</button>" + "</div>"
);
}
});
});
});
Controller Side:
I am having trouble passing data from my view to my controller. I am using checkboxes. For my view, I created a class that takes in all my checkboxes (Mon-Fri) and putting them into a list (so I can use the data someplace else). My problem is that when I debug and click the checkboxes on the website, the code does not change whether I click the checkbox or not, so my code doesn't recognize the checkbox data
I'm not sure if I have implemented the View incorrectly but any help to the right direction would be appreciated !
ViewModel:
public List<cDay> _cDays = new List <cDay>();
public List<cDay> cDays
{
get {return _cDays;}
set {_cDays = value;}
}
public class cDay
{
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
}
CSHtml file:
#Html.Label("M")
#Html.CheckBox("Monday", false, new { #class = "availability" })
// this is basically the same code for Tuesday-Friday as well.
'<label for="M">M</label> +
'<input class="availability" id="Monday" name="Monday" type="checkbox" value="true">' +
'input name="Monday" type="hidden" value="false">'
// this is basically the same code for Tuesday-Friday, but the "name" corresponds to each day
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string inputValue, Model viewModel)
{
if(ModelState.IsValid)
//
}
Consider to use the following data model:
public class DaysViewModel
{
public List<CDay> Days { get; set; } = new List<CDay>();
}
public class CDay
{
public CDay()
{
Name = string.Empty;
Selected = false;
}
public CDay(string name)
{
Name = name;
Selected = false;
}
[Required]
public string Name { get; set; }
[Required]
public bool Selected { get; set; }
}
Then you can use the default ASP.NET MVC data binding without a JS support:
#model Models.DaysViewModel
#using (Html.BeginForm("Edit", "Home"))
{
#Html.AntiForgeryToken()
for(int i=0; i < Model.Days.Count; i++)
{
<div class="form-group row">
#Html.CheckBox("Days[" + i + "].Selected", Model.Days[i].Selected)
#Html.Hidden("Days[" + i + "].Name", Model.Days[i].Name)
<span>#Model.Days[i].Name </span>
</div>
}
<input type="submit" value="Save" />
}
And on the server side:
public ActionResult Edit()
{
var model = new DaysViewModel();
model.Days.AddRange( new List<CDay> {
new CDay("Monday"),
new CDay("Tuesday"),
new CDay("Wednesday"),
new CDay("Thursday"),
new CDay("Friday")
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(List<CDay> days)
{
if(ModelState.IsValid)
{
// ... you_code here
}
var model = new DaysViewModel() { Days = days };
return View(model);
}
Test screen shots
The view:
On the controller side:
You can do it using jQuery
Add a button bellow your checkboxes
<input type="button" value="Your_Value" class="btn btn-default" />
When click on a button create a post request and sends checked status via querystring
$(document).ready(function () {
$("input[type=button]").click(function () {
var queryString = 'Monday=' + $("input[name=Monday]").is(":checked") + '&Tuesday=' + $("input[name=Tuesday]").is(":checked") + '&Wednesday=' + $("input[name=Wednesday]").is(":checked") + '&Thursday=' + $("input[name=Thursday]").is(":checked") + '&Friday=' + $("input[name=Friday]").is(":checked");
$.ajax({
type: "Post",
url: "/Home/Edit?" + queryString,
success: function (data) {
},
error: function (data) {
}
});
});
});
And inside controller create Edit Post Method like this
[HttpPost]
public ActionResult checkboxespost(string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
{
...
}
Part of my index.html contains 3 buttons-anchors like this (There is some bootstrap as well)
Index.html
<a id="category1" href="html/auctionBay.html" class="portfolio-link" >
<a id="category2" href="html/auctionBay.html" class="portfolio-link" >
<a id="category3" href="html/auctionBay.html" class="portfolio-link" >
These buttons redirect me to the auctionBay.html which contains a div
auctionBay.html
<div id="result" class="container"></div>
What i need, is when i press a button from the above, to go to the auctionBay.html and accordingly to what was pressed, print the data from the appropriate table (category1-3) from my database into the 'result' div (it's important to be in the div).
I currently have a servlet that can do this statically when auction.html loads using an ajax call
var j = jQuery.noConflict();
function myFunction() {
j.ajax({
type : 'GET',
url : '../auctionsDisplay',
success : function(data) {
j("#result").html(data);
}
});
}
but only works if i specify the category manually.(antiques=category1 for example)
AuctionDisplay.java
public class AuctionsDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String result = "";
try {
Connection con = DBConnection.getCon();
String category = "antiques";
String query = "select id, name, price from " + category;
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
int i;
result = "";
boolean flag = rs.next();
while (flag) {
result += "<div class='container'><div class='row'><h1 id='antiques' class='category'>Antiques</h1></div><div class='row'>";
i = 0;
while (i < 4 && flag) {
ps = con.prepareStatement("select highestBidder, ends from auctions where itemId=?");
ps.setString(1, rs.getString("id"));
ResultSet rs2 = ps.executeQuery();
rs2.next();
String price = rs.getString("price");
if (rs2.getString("highestBidder") != null)
price = rs2.getString("highestBidder");
result += "<div class='col-md-3' portfolio-item>";
result += "<div class='w3-container w3-hover-shadow w3-center'>" + "<h2>" + rs.getString("name")
+ "</h2><div class='w3-card-20' style='width:100%'>"
+ "<input id='2' type='image' src='../img/portfolio/w3.jpg' data-toggle='modal' "
+ "data-target='#MoreInfo'style='width:90%;'>"
+ "<div class='w3-container w3-center responsive'>"
+ "<p style='padding:5px;'>Highest Bid: " + price + "\u20ac <br> " + "Ends at: "
+ rs2.getString("ends") + "<p></div></div></div></div>";
flag = rs.next();
i++;
}
result += "</div></div>";
}
} catch (Exception e) {
e.printStackTrace();
}
out.println(result);
}
I understand jquery, ajax, get-post requests, javascript (no php please), so how can i achieve what i want ? It's propably simple but it's confusing me
You can achieve what you want in javascript thanks to window.LocalStorage. Since you want your data from one page to be sent to another page(where the browser loads a whole new page which results in the loss of any data retrieved by the last page), via javascript you WILL need to make use of localStorage to get the desired results.
How to?
var j = jQuery.noConflict();
function myFunction(category_id) {
//use this id to fetch your appropriate data
j.ajax({
type : 'GET',
url : '../auctionsDisplay',
success : function(data) {
localStorage.setItem("category_result", data);
}
});
}
j('.portfolio-link').click(function(){
var category_id = this.id //this will give you the pressed <a>'s ID value
myFunction(category_id);
})
//then on document load retrieve the localStorage value you stored.
$(document).ready(function () {
if (localStorage.getItem("category_result") !== null) {
//feed the value to the 'results' div
j('#result').html(localStorage.getItem("category_result"));
}
}
Let me know if this helped
Hope one kindly can help me, it may be a simple question but frustrated me as there is no fix for it,
I want to pass value from a hidden field to controller via model binding,
no matter what approach I use, just passing the value from view to controller via model can work for me,
this is my slider range
<label for="amount">دامنه قیمت:</label>
<div id="connect" class="noUi-target noUi-ltr noUi-horizontal noUi-background">
</div>
this is the hidden field,
<input type="hidden" name="MinPrice" value="#Model.MinPrice" id="MinPrice" />
<input type="hidden" name="MaxPrice" value="#Model.MaxPrice" id="MaxPrice" />
< script >
var connectSlider = document.getElementById('connect');
noUiSlider.create(connectSlider, {
start: [40000, 800000],
connect: true,
range: {
'min': 0,
'max': 2000000
}
}); < /script>
<script>
var connectBar = document.createElement('div'),
connectBase = connectSlider.querySelector('.noUi-base');
/ / Give the bar a class
for styling and add it to the slider.
connectBar.className += 'connect';
connectBase.appendChild(connectBar);
connectSlider.noUiSlider.on('update', function(values, handle, a, b, handlePositions) {
var offset = handlePositions[handle];
// Right offset is 100% - left offset
if (handle === 1) {
offset = 100 - offset;
}
// Pick left for the first handle, right for the second.
connectBar.style[handle ? 'right' : 'left'] = offset + '%';
}); < /script>
<script>
var valueInput = document.getElementById('MinPrice'),
valueSpan = document.getElementById('MaxPrice');
/ / When the slider value changes, update the input and span
connectSlider.noUiSlider.on('update', function(values, handle) {
if (handle) {
valueInput.value = values[handle];
} else {
valueSpan.innerHTML = values[handle];
}
});
// When the input changes, set the slider value
valueInput.addEventListener('change', function() {
connectSlider.noUiSlider.set([null, this.value]);
});
< /script>
this is my JS that fill the hidden field, these two fields are filled correctly, but dont send data to controller via model,
thank you all pal,
Updated
this is my model:
public class SearchModel
{
public string Devision { get; set; }
public string Gender { get; set; }
public int? MinPrice { get; set; }
public int? MaxPrice { get; set; }
public string Brand { get; set; }
public string Sport { get; set; }
public string Size { get; set; }
public string ProductGroup { get; set; }
public List<tblSiteItem> Result { get; set; }
public List<tblSiteItem> Sales { get; set; }
public List<string> Devisions { get; set; }
public List<string> Genders { get; set; }
public List<string> Brands { get; set; }
public List<string> Sports { get; set; }
public List<string> Sizes { get; set; }
public List<string> ProductGroups { get; set; }
public List<tblSiteCart> CartItems { get; set; }
public int PageNo { get; set; }
public int Barcode { get; set; }
}
As I said the value is filled correctly so I do not need code to make it corrected, Just not bind the hdnValue to the field in my model.
I mean MinPrice and MaxPrice.
Edited
I am not allowed to upload images sadly, If I were everything was pretty obvious to look at,
any way, I explain the detail:
when I change the slideBar, my JS fires and values change,
when I click the search button all the fields in my model is field except for these two field , I mean MinPrice and MaxPrice
result shows an empty page , again my Js keep fired then come back to the default values,
in the last try I changed the hidden field to type="text"
and saw that when I change the slidebar the value is in my text box but not binded to my view model when touch search button.
I am sure there is something wrong with my viewmodel, but How I can understand what is incorrect :( please kindly look at my code
The names of your inputs are incorrect. You should remove the Model. part from it. If you used HtmlHelper.HiddenFor, you'd get the following:
<input type="hidden" name="MaxPrice" value="#Model.MaxPrice" id="MaxPrice" />
This way, the inputs will get submitted to your model correctly.
Have a look at this answer.
Use this code for get the value:
var userRole = "";
userRole = $("#hdnVal").val();
alert(userRole);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hdnVal" value="#Model.MinPrice" />
Follow this.
On .cshtml Page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hdnVal" value="#Model.MinPrice" />
<input type="button" name="Submit" value="Submit" id="btnSubmit" class="btn btn-primary" />
Js
var userRole = "";
userRole = $("#hdnVal").val();
alert(userRole);
$('#btnSubmit').click(function() {
var formData = new FormData();
formData.append("userRole ", userRole);
$.ajax({
type: "POST",
url: "/Controller/YourAction/",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(result) {
if (result.Message == "success") {
alert("Success");
}
}
});
}
C# Code
public JsonResult YourAction()
{
string Role = Request.Form["userRole "];
//You can get the value of role
}
I had the same problem and after several test I found the solution sending values via ajax but building the data for the request in a string JSON format, where the hidden fields, are written without single quotes and the other fields with single quotes. Below is shown the example. I hope that this variant help you.
JavaScript code to send data to controller
$("#saveSearchModel").on("click", function (e) {
e.preventDefault();
// Variables for fields values
var devision = $("#Devision").val();
var gender = $("#Gender").val();
var minPrice = $("#MinPrice").val();
var maxPrice = $("#MaxPrice").val();
var brand = $("#Brand").val();
/*
Get the other fields...
*/
// Data for pass to controller via ajax
var data1 = "{'Devision':'" + devision + "','Gender':'" + gender + "',MinPrice:" + minPrice + ",MaxPrice:" + maxPrice + ",'Brand':'" + brand + /*Add the other fields...*/ + "'}";
$.ajax({
url: '/Controller/Action1',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: data1,
success: function (result) {
// Do something
}
});
});
Code in controller to receive data
[HttpPost]
public void Action1(SearchModel model)
{
// Gets the values of model
string devision = model.Devision;
string gender = model.Gender;
int? minPrice = model.MinPrice;
int? maxPrice = model.MaxPrice;
string brand = model.Brand;
/*
Gets the others values of model...
*/
}
I'm developing an asp.net mvc 5 online store project . I want to create cart to add Goods with Cookie . I'm confused about it and don't know why it didn't work . it didn't gave me any error . also I add break points to debug it but any data didn't send to my actions !
could anyone help me ? what's the problem ?
I'm not good in javascript and I think problem would be in javascript codes :/
Thanks in advance
Goods controller
[HttpPost]
public ActionResult AddToCart(int Id, int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product added to your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("product didn't add to your basket", MessageType.Error).Script,
Html = ""
});
}
}
public ActionResult RemoveCart(int Id)
{
try
{
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
Request.Cookies["NishtmanCart_" + Id.ToString()].Expires = DateTime.Now.AddDays(-1);
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product removed from your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
else
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("this product doesn't have in your basket", MessageType.Warning).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product didn't remove from your basket", MessageType.Error).Script,
Html = ""
});
}
}
MyJsonData.cs
public class MyJsonData
{
public string Script { get; set; }
public string Html { get; set; }
public bool Success { get; set; }
}
_GoodDetailsAjax.cshtml
#foreach (var item in Model.GoodDetails)
{
<div>
<p class="nowprice">NowPrice : #item.DetailsNowPrice</p>
<p class="preprice">PrePrice : #item.DetailsPrePrice</p>
<a class="button icon-cart" href="#" GoodID="#item.DetailsGoodID">Add to cart</a><br>
<a class="link" >Shopping Cart (0)</a>
</div>
}
#section scripts{
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
$(function () {
$("a.button.icon-cart").click(function (e) {
e.preventDefault();
var goodId = $(this).attr("GoodID");
alert(goodId); //////// I just added this code
$.ajax({
url: "/Goods/AddToCart",
data: { Id: goodId, Count: 1 },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("Error!");
}
});
});
});
</script>
}
I don't know what's the implementation of MessageBox.Show("....", MessageType.Error).Script but I'm assuming that it just generates a simple JavaScript statement like this:
Script = "alert('product added to your basket');"
So you can add this tag for the result:
<div id="CartItems">
</div>
Now it works without any problem.
All of my codes was true , I just made some simple mistakes .
I loaded a JQuery file in my layout and also I loaded another version of JQuery in my view! I deleted one of them .
And also I used those codes in a partial view and loaded they using Ajax but my partial view couldn't pass data to Controller , I moved codes to main view (GoodDetails.cshtml) and it works fine now .