将Javascript变量发送到MVC控制器
单击链接时,我需要向MVC中的某个C控制器发送一个JavaScript变量。我不想用Jquery来做这件事。我需要用JavaScript来做 以下是控制器的代码:将Javascript变量发送到MVC控制器,javascript,c#,asp.net,model-view-controller,Javascript,C#,Asp.net,Model View Controller,单击链接时,我需要向MVC中的某个C控制器发送一个JavaScript变量。我不想用Jquery来做这件事。我需要用JavaScript来做 以下是控制器的代码: **[HttpPost] public ActionResult saveuser(int id, string propertyName, string value) { var status = false; var message = "";
**[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,第二个是元素的属性名,第三个是元素的值。谢谢,如果我理解您在这里尝试的是使用纯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();
}
你说你不想使用jQuery,但你用AJAX标记了这篇文章,AJAX是jQuery的一部分。还有,到目前为止你到底尝试了什么?大量的教程演示了基础知识。你需要分享相关的代码。我已经在帖子中添加了相关的代码。谢谢,我们需要看看你的控制器,你正在使用标题吗?身体查询字符串?我们不知道服务器期望的是什么。谢谢,但这缺少了如何向控制器发送三个参数。@AhmedLassar I添加了参数,使用了基于Nikola答案的查询字符串的语法。没有理由添加另一个答案来执行他所提供的内容。如果控制器的名称为ShiftTypes,操作结果为saveuser,那么它还不起作用,请提供控制器的url。如何调用它而不是google.com然后您将执行/ShiftTypes/SaveUser?id=8&propertyName=name&value=value’。您可能想尝试进一步了解基本原理,这样会得到更好的帮助。下面是函数及其不工作的情况,函数callYourControllerid,propertyName,value{var xhttp=new XMLHttpRequest;xhttp.onreadystatechange=function{如果this.readyState==4&&this.status==200{console.logthis.responseText;};xhttp.openPOST,/ShiftTypes/saveuser?id=8&propertyName=SFY\u Name&value=testvalue,true;xhttp.send;}