簡體   English   中英

來自 javascript 的 asp.net MVC 調用控制器

[英]asp.net MVC call controller from javascript

有沒有一種方法可以使用視圖中的 javascript 從控制器調用我的插入函數

這是我的控制器:

       public ActionResult Update(int a, string b)
        {
            string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = @a WHERE b = @b ", con);
                //cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@a", a);
                cmd.Parameters.AddWithValue("@b", b);                
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            return RedirectToAction("Index");
        }

這是我的 javascript,它包含來自 HTML 的值

     function SaveChanges() {
        var a = document.getElementById("a").value
        var b = document.getElementById("b").value

        //TODO: pass the variables to the controller to perform insert query
    }

任何建議或意見。 TIA。

請試試這個:

 function submit(){
    var a = document.getElementById("a").value;
    var b = document.getElementById("b").value;
    $.ajax({
      url: '/ControllerName/Update(ActionResult)/' 
      type: 'post',
      contentType: 'application/json',
      data: {
        'a':a,
        'b':b
      },
      success: function(data){
        alert('success');
      }, 
      error: function(xhr, textStatus, error){
      alert(xhr.statusText);
      alert(textStatus);
      alert(error);
  }
      }
    });

你想要的是使用 AJAX 回調從客戶端調用控制器動作,它應該像下面的例子一樣設置:

JS函數

function SaveChanges() {
    // input values
    // the variable names intentionally changed to avoid confusion
    var aval = $('#a').val();
    var bval = $('#b').val();

    var param = { a: aval, b: bval };

    $.ajax({
        type: 'POST',
        url: '@Url.Action("Update", "ControllerName")',
        data: param,
        // other AJAX settings
        success: function (result) {
            alert("Successfully saved");
            location.href = result; // redirect to index page
        }
        error: function (xhr, status, err) {
            // error handling
        }
    });
}

然后將[HttpPost]屬性添加到控制器操作並返回包含要重定向的 URL 的 JSON 數據,因為RedirectToAction()無法與 AJAX 回調正常工作:

控制器動作

[HttpPost]
public ActionResult Update(int a, string b)
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = @a WHERE b = @b ", con);
        cmd.Parameters.AddWithValue("@a", a);
        cmd.Parameters.AddWithValue("@b", b);                
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

    // create URL and return to view
    string redirectUrl = Url.Action("Index", "ControllerName");

    return Json(redirectUrl);
}

請注意,這只是一個簡單的示例,您可以使用try...catch異常處理和此處未提及的其他內容進行改進。

您應該為此使用 jquery Ajax POST 方法。 比如這個結構...

function submit(){
var a = document.getElementById("a").value
var b = document.getElementById("b").value
$.ajax({
  url: '/ControllerName/Update/' 
  dataType: 'text',
  type: 'post',
  contentType: 'application/json',
  data: {
    'a':a,
    'b':b
  },
  success: function( data, textStatus, jQxhr ){
    alert('success')
    console.log(data)
  }, 
  error: function( jqXhr, textStatus, errorThrown ){
    console.log( errorThrown );
  }
});

控制器代碼

public ActionResult Update(int a, string b)
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = @a WHERE b = @b ", con);
        //cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@a", a);
        cmd.Parameters.AddWithValue("@b", b);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    return RedirectToAction("Index");
}

.cshtml 代碼

function SaveChanges() {
  var a = document.getElementById("a").value;
  var b = document.getElementById("b").value;

  $.ajax({
    type: 'GET',
    url: '@Url.Action("Update")',
    data: {
      'a': a,
      'b': b
    },
    success: function(result) {
      alert("Successfully saved");
    },
    error: function(xhr, status, err) {
      // error handling code
    }
  });
}

您需要在提交按鈕單擊事件上調用SaveChanges()函數。 根據您的參考代碼,我必須將該方法設為GET ,如果您在控制器端的方法是POST ,那么在AJAX方法中,您需要將方法類型GET更改為POST

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM