I'm trying update status of every each Message from unread to read and when i click on button of first message in the list updating status going to work,but when i click on button of second or Third message in the list updating status NOT going to work. Can anyone please help me or point me in the right direction!
Thanks in advance :)
View:
<div class="content">
@{ int i = 0;}
foreach (var item in Model.Comment_Lists.GroupBy(l => l.MSG).Select(g => .First())) {
if (item.se == "Kunde")
{
<div class="bs-callout bs-callout-success">
<div class="col-xs-3 text-right">
<button data-toggle="collapse" data-target="#ShowMSG_@i" id="btnChangestu" class="btn btn-sm btn-success btn-icon"></button></div>
<span class="text-muted"><small> @item.Date.ToString("dd/MMMM/yyy")</small></span><br />
<span class="text-muted"><small> @item.MSGType</small></span>
<input type="hidden" name="IDMSG" id="IDMSG" value="@item.id" />
<input type="hidden" name="ChangeStu" id="ChangeStu" value="Read Message" />
<div class="collapse" id="ShowMSG_@i">
<p><span>@item.MSG </span></p>
</div>
</div>
}
i++;
}
</div>
JavaScript:
<script>
$(document).ready(function () {
$("#btnChangestu").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/Account/UpdateMSGStatus",
data: {
IDMSG: $("#IDMSG").val(),
ChangeStu: $("#ChangeStu").val()
},
dataType: 'json',
success: function (result) {
if (!$.trim(result)) {
alert("What follows is blank: ");
}
else {
result.ID = IDMSG;
result.MSGType = ChangeStu;
console.log("Send");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
})
});
});
</script>
Controller:
public JsonResult UpdateMSGStatus(int? IDMSG , string ChangeStu)
{
var u = db.Besked.Where(a => a.ID == IDMSG).FirstOrDefault();
if (u != null)
{
u.MSGType = ChangeStu;
u.ID = IDMSG;
db.SaveChanges();
}
return Json(u, JsonRequestBehavior.AllowGet);
}
Duplicate id
attributes are invalid html, and your jQuery selectors ( IDMSG: $("#IDMSG").val()
etc) will only ever select the first element with that id
.
There is no reason to use hidden inputs in this case. Instead, ad the values as data
attributes and read then in the .click()
event, and use a class
name for the button instead of an id
.
Note I have only included the IDMSG
, not ChangeStu
since you have hard coded that value
<button data-id="@item.id" class="btn btn-sm btn-success btn-icon edit" data-toggle="collapse" data-target="#ShowMSG_@i></button>
Then the script becomes
$('.edit.).click(function (e) {
e.preventDefault();
// read the value
var id = $(this).data('id');
$.ajax({
type: "POST",
url: '@Url.Action("UpdateMSGStatus", "Account"), // don't hard code urls
data: {
IDMSG: id,
ChangeStu: 'Read Message'
},
dataType: 'json',
success: function (result) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.