[英]Calling a HTTP POST method in a MVC Controller from the View's Javascript & Database saving
I am trying to update a value in my database. 我正在尝试更新数据库中的值。 When the user presses the update button this script is called. 当用户按下更新按钮时,将调用此脚本。
View Code: 查看代码:
<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>
In the controller, the value is then revived and saved into the database. 然后在控制器中将值恢复并保存到数据库中。 A message is sent back to let the user know their quote was updated. 发送一条消息,让用户知道其报价已更新。
Controller Code: 控制器代码:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
*REPLACE QUOTE IN DATABASE*
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
I am having difficulty finding out how to write the code described between the **'s (For the database part I have a user-id that can be used to identify the row) 我很难找出如何编写在**之间描述的代码(对于数据库部分,我有一个可用于标识行的用户ID)
You can use form posting like this: 您可以像这样使用表单发布:
$("#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
});
})
or you can use an ajax post: 或者您可以使用ajax发布:
$.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
}
});
For using the data, assuming you have an DbContext
called MyDbContext
: 对于使用中的数据,假设你有一个DbContext
称为MyDbContext
:
[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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.