如何使Angular POST到C#Asp.Net MVC控制器? [英] How to make Angular POST to C# Asp.Net MVC Controller?

查看:123
本文介绍了如何使Angular POST到C#Asp.Net MVC控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,但没有发现任何可以成功调用MVC Controller的内容(Angular post).我知道那里有很多Angular/.Net开发人员.我可以帮忙吗?

I have looked around, but have not found anything (Angular post) that can actually make a successful call to a MVC Controller. I know there are a lot of Angular/.Net devs out there. Can I get some help?

让我们简单地回答问题吧!

如果我在控制器上设置了换行符,则可以看到此代码实际上并没有击中控制器.

If I set a linebreak on the controller, I can see that this code is not actually hitting the controller.

HTML

<!-- I click this button -->
<input type="button" value="click" onclick="postit()" />

Javascript/Angular Post

Javascript/Angular Post

function postit() {
 $http({
        method: 'POST',
        url: 'Home/Give/',
        data: { id: 4 }
    }).success(successFn).error(errorFn);
}

function successFn() {
    alert("success");
}

MVC C#控制器

    [AcceptVerbs("OPTIONS")]
    public ActionResult Give(int id)
    {
        var response = "some response" + id.ToString();
        return Json(new JavaScriptSerializer().Serialize(response)); 
     }

推荐答案

国王Puppy,我已经看到一些响应,这些响应指示控制器参数应该是与要发送的对象匹配的对象,但是,看来比这还宽容得多.考虑以下示例(我对您的功能进行了一些更新):

king Puppy, I've seen a few responses that dictate that the controller parameters should be an object that matches the object that is being sent, however, it seems that it's a little more forgiving than that. Consider the following example (I've updated your function a little):

Javascript:

Javascript:

$scope.postIt = function() {
  var data = {
    id = 4
  };

  $http
    .post('Home/Give', data)
    .success(function(data, status, headers, config) {
      successFn();
    })
    .errors(function(data, status, headers, config) {
      errorFn();
    });
};


function successFn() {
  alert("success");
};

function errorFn() {
  alert("error");
};

MVC:

 public ActionResult Give(int id)
 {
   var response = "some response" + id.ToString();

   return Json(new JavaScriptSerializer().Serialize(response)); 
 }

如果设置了一个断点,您将看到传入的ID为4.

If you set a breakpoint, you will see that the id passed in is 4.

如果您需要传递一个对象(不止一个id),则可以在控制器端创建匹配的类或结构,也可以具有多个参数(前提是它们是简单的值类型) 即:

If you needed to pass in an object (so more than just one id), you could either create a matching class or struct on the controller side, or have multiple parameters (provided that they are simple value types) ie:

public JsonResult Give (int id, int reasonId)
{
 ... 
}

无论如何,我知道该职位已过时,但也许会对您或其他人有所帮助.

Anyway, I realize the post is old, but perhaps it will help you or others.

这篇关于如何使Angular POST到C#Asp.Net MVC控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆