【发布时间】:2016-04-25 23:29:20
【问题描述】:
我想在 asp.net MVC5 中使用 Ajax 更新文本框的值(包含 cookie 的值)。我是 JavaScript 的新手,我编写了这些代码,但我的代码不起作用。我没有收到任何错误,但它不起作用。我在外部文件“UpdateTxtBox.js”中编写了 JavaScript,并在 Layout 中添加了 <script src="~/Scripts/UpdateTxtBox.js"></script>。
谁能告诉我这是什么问题?
$(function () {
$("textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
Basket.cshtml的一部分
@using (Html.BeginForm("AddToCart", "Goods", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(modelItem => item.Count, new { @class="text textCountProduct" , style="width:40px;" , productid=item.GoodDetails.DetailsGoodID})
}
好的控制器
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);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
//Script = "alert('Good added successfully');",
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
更新帖子: 我在控制器操作结果中添加了 [HttpPost] 并向 javascript 添加了一些警报
$(function () {
alert("aleeeert");
$(".textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
alert(count);
alert(id);
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
它工作正常,但是当我刷新页面时,数据没有保存
【问题讨论】:
-
你在这里犯了错误
$("textCountProduct")使用.作为selector。应该是$(".textCountProduct") -
谢谢,我更正了它,但它还没有工作@ParthTrivedi
-
请检查您的浏览器控制台。 ajax 调用了吗?
-
控制台没有错误。这意味着ajax被称为? @ParthTrivedi
-
更改执行时网络中没有 ajax 请求显示。
标签: javascript jquery ajax asp.net-mvc