【问题标题】:Send Javascript Vairable To C# MVC controller [closed]将 Javascript 变量发送到 C# MVC 控制器 [关闭]
【发布时间】:2019-08-05 11:45:56
【问题描述】:

单击链接时,我需要将 JavaScript 变量发送到 MVC 中的某个 C# 控制器。我不想用 Jquery 来做。我需要用 JavaScript 来做。

这是控制器的代码:

 **[HttpPost]
        public ActionResult saveuser(int id, string propertyName, string value)
        {
            var status = false;
            var message = "";
            //Update data to database 

            using (PaediatricDBEntities db = new PaediatricDBEntities())
            {
                var user = db.ShiftTypes.Find(id);
                if (user != null)
                {
                    db.Entry(user).Property(propertyName).CurrentValue = value;
                    db.SaveChanges();
                    status = true;
                }
                else
                {
                    message = "Error!";
                }
            }
            var response = new { value = value, status = status, message = message };
            JObject o = JObject.FromObject(response);
            return Content(o.ToString());
        }**

我需要通过javascript向这个控制器发送3个参数,第一个是元素的id,第二个是元素的属性名,第三个是元素的值。谢谢,

【问题讨论】:

  • 你说你不想使用 jQuery,但你用 AJAX 标记了这篇文章,它是 jQuery 的一部分。另外,到目前为止,您到底尝试了什么?
  • 大量教程展示了基础知识。
  • 需要分享相关代码。
  • 我已经在帖子中添加了相关代码。谢谢,
  • 我们需要查看您的控制器,您使用的是标头吗?身体?请求参数?我们不知道服务器期望什么。

标签: javascript c# asp.net model-view-controller


【解决方案1】:

如果我理解您在这里尝试做的是使用纯 javascript 调用端点?

这将为您完成工作:

function callYourController(id, propertyName, value) {
   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
           console.log(this.responseText);
       }
   };
   xhttp.open("POST", "www.google.com?id=" + id + "&propertyName=" + propertyName + "&value=" + value, true);
   xhttp.send();
}

【讨论】:

  • 谢谢,但是这里缺少如何向控制器发送三个参数。
  • @AhmedElassar 我添加了带有语法的参数,以使用基于 Nikola 答案的查询字符串。没有理由添加另一个答案来做他提供的实质内容。
  • 它还没有工作,如果控制器的名称是ShiftTypes并且Action Result是saveuser,请提供控制器的url。如何调用它而不是 google.com
  • 那么你会做 /ShiftTypes/SaveUser?id=8&propertyName=name&value=value' 。您可能想尝试更多地了解基础知识,您会在 SO 上获得更好的帮助。
  • 这里是函数,它不工作,函数 callYourController(id, propertyName, value) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; xhttp.open("POST", "/ShiftTypes/saveuser?id=8&propertyName=SFY_Name&value=testvalue", true); xhttp.send(); }
猜你喜欢
  • 2019-05-31
  • 1970-01-01
  • 2014-03-17
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多