[英]How to update database with ajax/javascript without refreshing page asp.net mvc
我想通過做一些ajax調用而不刷新我的頁面,在我的數據庫中將枚舉列表的值從活動更改為非活動狀態? 我該怎么做呢? javascript方法還是ajax.beginform? 這里不確定......
我嘗試了ajax.beginform並且調用得到了控制器ok,但之后它嘗試通過將其作為actionresult返回來刷新/渲染視圖。 我不希望它刷新視圖,因為我丟失了我的viewmodel數據。 我以為ajax.beginform只刷新了表單里面的內容? 我需要在javascript方法中執行此操作嗎? 如何防止在我的操作方法中刷新/呈現視圖?
這是我的ajax表格。 如果我返回一個視圖,我會丟失所有“模型”視圖數據,因此model.statusenabled為null! 我不明白為什么它是null因為它在ajaxform之外......
@if (Model.StatusEnabled)
{
using (Ajax.BeginForm("UpdateStatus", "Student", new AjaxOptions
{
HttpMethod = "post",
OnSuccess = "dotcolor();"
}))
{
@Html.EnumDropDownListFor(model => model.Status, new { @class = "btn btn-default btn-lg dropdown-toggle", onchange = "this.form.submit();", id = "enumstatus" })
}
}
else
{
@Html.EnumDropDownListFor(model => model.Status, new { @class = "btn btn-default btn-lg dropdown-toggle", disabled = "disabled" })
}
這是我的行動方法
[HttpPost]
public ActionResult UpdateStatus()
{
//update database
// don't return view because it gets refreshed
// and I have to re pass in my viewmodel
return View("Edit");
}
如果我在UpdateStatus()中將返回類型更改為void,它仍然會嘗試返回名為UpdateStatus的視圖。 不是我想要的。
使用jquery和ajax發布所選值相對容易
HTML
@Html.EnumDropDownListFor(m => m.Status, new { @class = "btn btn-default btn-lg dropdown-toggle" })
腳本
var id = '@Model.ID'; // store the ID of the student (change to suit your property name)
var url = '@Url.Action("UpdateStatus", "Student")';
$('#Status').change(function() {
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function(data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
}
}
調節器
[HttpPost]
public ActionResult UpdateStatus(int ID, EmployeeStatus Status) // assumes the enum is typeof EmployeeStatus
{
// update the employees status based on the parameters
return Json(true); // or return Json("some message")
}
注意,您可能希望檢查狀態是否確實已更新,例如在catch塊中您可能return Json(null)
或return Json("some error message")
,然后您可以使用它來在頁面上顯示消息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.