0
我有一個HTML類似這樣的標記:發現在jQuery的POST數據元素,並更新DOM
@if (ViewBag.Added != null)
{
if (ViewBag.Added == false)
{
<div class="col-lg-2 col-md-3 col-sm-12 col-xs-12" id="wholeBtn">
<a class="btn btn-app btnWatchList" style="min-width:175px;margin:0;height:67px">
<i class="fa fa-save"></i> Add to Watchlist
</a>
</div>
}
else if (ViewBag.Added)
{
<div class="col-lg-2 col-md-3 col-sm-12 col-xs-12" id="addedToWatchList">
<h4>Added to watchlist</h4>
</div>
}
}
哪裏ViewBag.Added的是,我用它來檢查我是否有我的數據庫有相應的記錄的變量。 ..
我已經定義了一個上點擊事件當用戶點擊保存出現這樣的彈出按鈕裏面,然後我嘗試更新DOM:
$(document).on("click", ".btnSaveWatchlist", function(event)
{
StopLoading();
if ($('#TextArea1').val() == "" || !$('#ratingSystem input').is(':checked'))
{
ShowErrorMessage("All fields are required!");
return;
}
else
{
$.post("/SearchCompetitor/SaveWatchList",
{
comment: $('#TextArea1').val(),
rating: $('input[name=rating]:checked').val(),
competitor: $('.txtSearch').val()
}).done(function(data)
{
if (data == "AllFieldsRequired")
{
ShowErrorMessage("All fields are required!");
return;
}
else
{
$("#wholeBtn").hide();
var header = $('<div />').append(data).find('#addedToWatchList').html();
$('#addedToWatchList').html(header);
var l = document.getElementById('cancelButton');
l.click();
}
});
}
});
請注意我如何更新DOM本身:
$("#wholeBtn").hide();
var element = $('<div />').append(data).find('#addedToWatchList').html();
$('#addedToWatchList').html(element);
這是從服務器的方法的邏輯:
public ActionResult SaveWatchList(string comment, string rating, string competitor)
{
if (comment == "" || rating == "" || competitor == "")
return Json("AllFieldsRequired");
else
{
var user = ctx.Users.Where(x => x.Email == User.Identity.Name).FirstOrDefault();
var uwl = new UserWatchList()
{
Comment = comment,
Rating = Int32.Parse(rating),
Type = 0,
SellerFeedback = Int32.Parse(Session["score"].ToString()),
SentWord = competitor,
UserId = user.UserId
};
ctx.UserWatchList.Add(uwl);
ctx.SaveChanges();
ViewBag.Added = true;
return View("Index");
}
}
,我想有輸出是顯示HTML是:
else if (ViewBag.Added)
{
<div class="col-lg-2 col-md-3 col-sm-12 col-xs-12" id="addedToWatchList">
<h4>Added to watchlist</h4>
</div>
}
上午什麼我做錯了?
P.S.請注意,如果一切順利我通過Return View("Index");