从视图中调用MVC控制器中的HTTP POST方法'数据库保存
Calling a HTTP POST method in a MVC Controller from the View's Javascript & Database saving
我正在尝试更新数据库中的值。当用户按下更新按钮时,这个脚本被调用。
视图代码:
<script>
function scr_UpdateQuote(field) {
var r = confirm("Are you sure you want to update your quote?");
if (r == true) {
var textBox_UserTitle = document.getElementById(field);
*CODE TO POST METHOD HERE*
}
}
</script>
在控制器中,该值随后被恢复并保存到数据库中。返回一条消息,让用户知道他们的报价被更新了。
控制器代码:[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
*REPLACE QUOTE IN DATABASE*
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
我很难找出如何编写在**之间描述的代码(对于数据库部分,我有一个用户id,可用于标识行)
你可以这样使用表单:
$("#YourForm").submit(function() {
$.post("/YourController/UpdateQuote", $("#YourForm").serialize())
//this will serialize your form into:
// newQuote=someValue&&someOtherVariable=someOtherValue etc.
.done(function(data) {
// do what ever you want with the server response
});
})
或者您可以使用ajax post:
$.ajax({
type: "POST",
url: "/YourController/UpdateQuote",
data: {newQuote: document.getElementById(field)},
dataType: "json",
success: function(data) {
// do what ever you want with the server response
},
error: function(){
// error handling
}
});
对于使用数据,假设您有一个称为MyDbContext
的DbContext
:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
// get userID somehow, either from session, or pass as another parameter here
using (var dc = new MyDbContext)
{
var quoteToUpdate = dc.QuotesTable.FirstOrDefault(q => q.UserID == userID)
quoteToUpdate.quoteColumn = newQuote;
dc.SaveChanges();
}
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
相关文章:
- 当数据库中的某些内容发生变化时调用HTTP方法Meteor.js
- 验证数据并将其保存到数据库以供实时应用程序使用的正确方法
- 有没有一种方法可以使用javascript和节点模块(oracledb)将csv导入oracle数据库
- 在Sails/Waterline项目中,使用更新方法增加数据库值
- 在node.js和express中基于路径运行不同数据库查询的更好方法
- 有没有一种简单的方法可以通过javascript将MySQL文件导入SQLite数据库
- 我可以'我找不到一种将数据库源添加到dgrid的优雅方法
- 通知浏览器数据库更新的最佳方法
- 这是在网页中存储和使用从数据库加载的数据的最有效方法
- ASP.NET 检查数据库中是否存在电子邮件的最佳方法
- 一种使用 HTML5 的 localStorage 模拟数据库的方法
- Koa:在没有现有包装器的情况下连接到数据库的最明智的方法是什么?
- Javascript:有没有更好的方法在x次异步数据库/ ajax调用后执行函数
- 使用 JavaScript 连接数据库服务器的方法有多少种
- 有没有一种干净的方法来混合异步和同步数据库查询处理
- 在数据库中存储大量标记的最佳方法是什么
- 从数据库中选择父选项字段时填充子选项字段的简单方法)
- 有没有一种方法可以将每个文本区域自动调整为其大小's从数据库查询返回的数据
- 用数据库中的数据填充高图表的最佳(简单)方法
- 从视图中调用MVC控制器中的HTTP POST方法'数据库保存