我正在尝试使用jQuery异步更新数据库表字段。我成功地做到了但是我必须按F5刷新屏幕以查看更改。我试图获得包含数据库表字段的webgrid在其中一个字段通过异步更新进行更改时自动更新其内容的位置。
以下是工作的jQuery部分:
var printermapping =
{
"MTPrinterID": MTPrinterID,
"NTPrinterID": NTPrinterID,
"Active": "Y"
};
$.ajax({
url: '/Home/UpdatePrinterMapping/',
data: JSON.stringify(printermapping),
type: 'POST',
contentType: 'application/json; charset=utf-8',
});
所以我在家庭控制器中异步调用UpdatePrinterMapping Action。该行动看起来像:
public ActionResult UpdatePrinterMapping(PrinterMapping printermapping)
{
// Update printermapping to your db
var printer = db.PrinterMapping.Find(printermapping.MTPrinterID);
if (printer == null)
{
// this cannot happen according to current structure
}
else
{
try
{
db.Entry(printer).Member("Active").CurrentValue = printermapping.Active;
db.SaveChanges();
}
catch (Exception)
{
throw new Exception("General Exception occurred while saving to database");
}
}
return RedirectToAction("Index");
}
我的索引操作如下:
public ViewResult Index()
{
PrinterViewModel printerModel = new PrinterViewModel();
printerModel.Printers = from mapping in db.PrinterMapping select mapping;
return View(printerModel);
}
我的PrinterViewModel ViewModel看起来像:
public class PrinterViewModel
{
public PrinterMapping PrinterMapping;
public Exceptions Exceptions;
public IEnumerable<PrinterMapping> Printers;
public IEnumerable<SelectListItem> PrinterOptions
{
get { return new SelectList(new List<string>() { "Y", "N" }); }
}
}
其中PrinterMapping类是EF生成的数据类:
public partial class PrinterMapping
{
public string MTPrinterID { get; set; }
public string NTPrinterID { get; set; }
public string Active { get; set; }
}
这可能比需要的信息更多,但至少你拥有它。非常感谢你们所有人。