我正在做一个业余项目来自学 AngularJS 和 Web API 以及这两者如何很好地协同工作。
我有很好的 ASP.NET MVC 知识,但我仍然无法理解 AngularJS 和 Web API 以及这三者如何协同工作。
目前,我有一个带有以下代码的 Web API Controller :
public class PlanController : ApiController
{
[Route("api/thing")]
public HttpResponseMessage Post(ThingVM model)
{
HttpResponseMessage response;
if (ModelState.IsValid)
{
using (var context = new MyContext())
{
var thing = new Thing();
context.Thing.Add(thing);
context.SaveChanges();
response = Request.CreateResponse(HttpStatusCode.Created);
string uri = Url.Link("GetThingById", new {id = thing.Id});
response.Headers.Location = new Uri(uri);
}
}
else
{
response = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return response;
}
}
在我的 Create.cshtml View 中,我有 ng-app 指令,我创建了一个 JS Controller 并放置了 ng-controller表单周围的指令,并将其指向 JS Controller 。
但是我卡在这里了。首先,如何将我的 ThingVM.cs ViewModel 绑定(bind)到 Angular?我是否需要在我的 MVC Controller 上返回一个 JSONResult?如果是,如何?因为我尝试了以下内容,但它没有编译。
[HttpGet]
public JsonResult Create()
{
using (var context = new MyContext())
{
var model = new ThingVM();
return Json(model);
}
}
假设我让它工作,我如何将它绑定(bind)到 AngularJS,以便它知道我的 ViewModel 结构是什么样的?因为我的 ThingVM 有很多级别的复杂性。
最后,我如何处理表单提交,以便 POST 请求的 Angular 指向我的 Web API Controller 。
最佳答案
在像 Angular 这样的 MVC SPA 中,您应该将模型与 View 分开。我建议您的 asp.mvc 是您提供 View (HTML) 的地方,而您的 asp.net web api 是您提供具有 CRUD 操作的模型 (JSON) 的地方。
你的 asp.net mvc Controller :
[HttpGet]
public ActionResult Create()
{
return View(); //this return Create.cshtml
}
您的 asp.net api Controller :
public class PlanController : ApiController
{
public ThingVM Get()
{
using (var context = new MyContext())
{
var model = new ThingVM();
return model;
}
}
public HttpResponseMessage Post(ThingVM model)
{
HttpResponseMessage response;
//It's better to write the modelstate validation as an attribute. See improvement suggestion below
if (ModelState.IsValid)
{
using (var context = new MyContext())
{
var thing = new Thing();
context.Thing.Add(thing);
context.SaveChanges();
response = Request.CreateResponse(HttpStatusCode.Created);
string uri = Url.Link("GetThingById", new {id = thing.Id});
response.Headers.Location = new Uri(uri);
}
}
else
{
response = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return response;
}
}
你的 Angular Controller ,这里我使用$http来快速演示。在真正的应用程序中,您可以尝试 angular resource创建一个 REST 客户端
app.controller("planController", function ($scope, $http){
$scope.thingVM = $http.get("api/Plan"); //load view model as json from web api
$scope.saveThingVM = function(){
http.post("api/Plan",$scope.thingVM); //send a post request to web api to update
}
});
您的 Create.cshtml 可能是这样的:
<form ng-submit="saveThingVM()" ng-controller="planController">
<input ng-model="thingVM.Name" type="text"></input>
<input type="submit">Save model</input>
</form>
改进建议:
模型验证是一个横切关注点,最好将逻辑写成一个属性来重用逻辑。看看我在 How can I centralize modelstate validation in asp.net mvc using action filters? 的另一个答案
关于c# - 带有 Web API 2 和 AngularJS 的 MVC5.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21503641/
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.
使用rspec-rails3.0+,测试设置分为spec_helper和rails_helper我注意到生成的spec_helper不需要'rspec/rails'。这会导致zeus崩溃:spec_helper.rb:5:in`':undefinedmethod`configure'forRSpec:Module(NoMethodError)对thisissue最常见的回应是需要'rspec/rails'。但这是否会破坏仅使用spec_helper拆分rails规范和PORO规范的全部目的?或者这无关紧要,因为Zeus无论如何都会预加载Rails?我应该在我的spec_helper中做
假设我有一个类A,里面有一些方法。假设stringmethodName是这些方法之一,我已经知道我想给它什么参数。它们在散列中{'param1'=>value1,'param2'=>value2}所以我有:params={'param1'=>value1,'param2'=>value2}a=A.new()a.send(methodName,value1,value2)#callmethodnamewithbothparams我希望能够通过传递我的哈希以某种方式调用该方法。这可能吗? 最佳答案 确保methodName是一个符号,而
当我进入Rails控制台时,我已将pry设置为加载代替irb。我找不到该页面或不记得如何将其恢复为默认行为,因为它似乎干扰了我的Rubymine调试器。有什么建议吗? 最佳答案 我刚发现问题,pry-railsgem。忘记了它的目的是让“railsconsole”打开pry。 关于ruby-on-rails-带有Pry的Rails控制台,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/question
我了解instance_eval和class_eval之间的基本区别。我在玩弄时发现的是一些涉及attr_accessor的奇怪东西。这是一个例子:A=Class.newA.class_eval{attr_accessor:x}a=A.newa.x="x"a.x=>"x"#...expectedA.instance_eval{attr_accessor:y}A.y="y"=>NoMethodError:undefinedmethod`y='forA:Classa.y="y"=>"y"#WHATTT?这是怎么回事:instance_eval没有访问我们的A类(对象)然后它实际上将它添加到
我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'
我想开始使用“Sinatra”框架进行编码,但我找不到该框架的“MVC”模式。是“MVC-Sinatra”模式或框架吗? 最佳答案 您可能想查看Padrino这是一个围绕Sinatra构建的框架,可为您的项目提供更“类似Rails”的感觉,但没有那么多隐藏的魔法。这是使用Sinatra可以做什么的一个很好的例子。虽然如果您需要开始使用这很好,但我个人建议您将它用作学习工具,以对您来说最有意义的方式使用Sinatra构建您自己的应用程序。写一些测试/期望,写一些代码,通过测试-重复:)至于ORM,你还应该结帐Sequel其中(imho
在Ruby(或Rails)中,我们可以做到new_params=params.merge({:order=>'asc'})现在new_params是一个带有添加键:order的散列。但是是否有一行可以返回带有已删除key的散列?线路new_params=params.delete(:order)不会工作,因为delete方法返回值,仅此而已。我们必须分3步完成吗?tmp_params=paramstmp_params.delete(:order)returntmp_params有没有更好的方法?因为我想做一个new_params=(params[:order].blank?||para