J86*_*J86 13 c# angularjs asp.net-web-api2 asp.net-mvc-5.1
我正在开展一个侧面项目来自学AngularJS和Web API,以及两者如何很好地协同工作.
我有很好的ASP.NET MVC知识,但我仍然无法理解AngularJS和Web API以及这三者如何协同工作.
目前,我有一个Web API控制器,其代码如下:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在我Create.cshtml看来,我有ng-app指令,我已经创建了一个JS控制器并将ng-controller指令放在表单周围,并将其指向JS控制器.
但在这里我被卡住了.首先,如何将ThingVM.csViewModel 绑定到Angular?我是否需要JSONResult在我的MVC控制器上返回?如果是,怎么样?因为我试过,以下,并没有编译.
[HttpGet]
public JsonResult Create()
{
using (var context = new MyContext())
{
var model = new ThingVM();
return Json(model);
}
}
Run Code Online (Sandbox Code Playgroud)
假设我可以使用它,如何将它绑定到AngularJS,以便它知道我的ViewModel结构是什么样的?因为我ThingVM有很多层次的复杂性.
最后,我如何处理表单提交,以便在我的Web API Controller上为POST请求提供角度点.
Kha*_* TO 13
在像角度一样的MVC SPA中,您应该将模型与视图分开.我建议您的asp.mvc是您提供意见的地方(HTML),您的asp.net web api是您通过CRUD操作为模型(JSON)提供服务的地方.
你的asp.net mvc控制器:
[HttpGet]
public ActionResult Create()
{
return View(); //this return Create.cshtml
}
Run Code Online (Sandbox Code Playgroud)
你的asp.net api控制器:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
你的角度控制器,我在这里$http用于快速演示.在真实的应用程序中,您可以尝试使用角度资源来创建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
}
});
Run Code Online (Sandbox Code Playgroud)
你Create.cshtml可能是这样的:
<form ng-submit="saveThingVM()" ng-controller="planController">
<input ng-model="thingVM.Name" type="text"></input>
<input type="submit">Save model</input>
</form>
Run Code Online (Sandbox Code Playgroud)
改进建议:
模型验证是一个跨领域的问题,最好将逻辑编写为重用逻辑的属性.看看我的另一个答案我如何使用动作过滤器在asp.net mvc中集中模型状态验证?
| 归档时间: |
|
| 查看次数: |
10876 次 |
| 最近记录: |