从视图中调用MVC控制器中的HTTP POST方法'数据库保存

Calling a HTTP POST method in a MVC Controller from the View's Javascript & Database saving

本文关键字:方法 数据库 保存 POST HTTP 调用 视图 MVC 控制器      更新时间:2023-09-26

我正在尝试更新数据库中的值。当用户按下更新按钮时,这个脚本被调用。

视图代码:

<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
            }
        });

对于使用数据,假设您有一个称为MyDbContextDbContext:

[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();
}
相关文章: