Sending PDF from jsPDF to controller via ajax - javascript

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:

Related

Passing Values from Checkboxes from View to Controller

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)
{
...
}

Ajax POST data not appearing in modal

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);
}

Update panel does not work after calling the function loginByFacebook()

I'm using Facebook Graph JSON responses in my code to deserialize the JSON string.
I created the class as follow.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="fb-root"></div>
Login with Facebook
<br /> <br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '<%= ecommerce.fblogin.FaceBookAppKey %>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML
oauth: true // enable OAuth 2.0
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
function loginByFacebook() {
FB.login(function (response) {
if (response.authResponse) {
FacebookLoggedIn(response);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
function FacebookLoggedIn(response) {
var loc = '/fblogin.aspx';
if (loc.indexOf('?') > -1)
window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
else
window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;
}
</script>
</form>
namespace ecommerce
{
public partial class fblogin : System.Web.UI.Page
{
public const string FaceBookAppKey = "xxxxxxxxxx";
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["access_token"])) return; //ERROR! No token returned from Facebook!!
//let's send an http-request to facebook using the token
string json = GetFacebookUserJSON(Request.QueryString["access_token"]);
//and Deserialize the JSON response
JavaScriptSerializer js = new JavaScriptSerializer();
FacebookUser oUser = js.Deserialize<FacebookUser>(json);
if (oUser != null)
{
Response.Write("Welcome, " + oUser.name);
Response.Write("<br />id, " + oUser.id);
Response.Write("<br />email, " + oUser.email);
Response.Write("<br />first_name, " + oUser.first_name);
Response.Write("<br />last_name, " + oUser.last_name);
Response.Write("<br />gender, " + oUser.gender);
Response.Write("<br />link, " + oUser.link);
Response.Write("<br />updated_time, " + oUser.updated_time);
Response.Write("<br />birthday, " + oUser.birthday);
Response.Write("<br />locale, " + oUser.locale);
Response.Write("<br />picture, " + oUser.picture);
if (oUser.location != null)
{
Response.Write("<br />locationid, " + oUser.location.id);
Response.Write("<br />location_name, " + oUser.location.name);
}
}
}
private static string GetFacebookUserJSON(string access_token)
{
string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link", access_token);
WebClient wc = new WebClient();
Stream data = wc.OpenRead(url);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
data.Close();
reader.Close();
return s;
}
public class FacebookUser
{
public long id { get; set; }
public string email { get; set; }
public string name
{ get; set; }
public string first_name
{ get; set; }
public string last_name
{ get; set; }
public string gender
{ get; set; }
public string link
{ get; set; }
public DateTime updated_time
{ get; set; }
public DateTime birthday
{ get; set; }
public string locale
{ get; set; }
public string picture
{ get; set; }
public FacebookLocation location
{ get; set; }
}
public class FacebookLocation
{
public string id
{ get; set; }
public string name
{ get; set; }
}
static int a = 0;
protected void Button1_Click(object sender, EventArgs e)
{
a++;
Label1.Text = Convert.ToString(a);
}
}
}
After added update panel my Facebook login function not working after the link is clicked.
I added AJAX page request manager. The post Back settings function it not work as what I expected.
After I remove added update panel works is working as I expect.
/** This is what I try, but not work */
function loginByFacebook() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm._postBackSettings(function (sender, e) {
if (sender.loginByFacebook.panelsToUpdate != null) {
loginByFacebook();
}
});
};
}
*/
Below is the screenshot issues i'm stuck.
Update panel events are rendered partially hence the events will looses.
After Login or Register Button is click. The Facebook login will not work as expected. The dialog box will not close automatically.

how to send hidden field to controller via model binding

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...
*/
}

why these cookie codes didn't work in asp.net mvc?

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 .

Categories

Resources