角ASP.NET MVC绑定 [英] Angular ASP.NET MVC Binding
问题描述
在我们的MVC 5项目中,我们使用Angular.以下剃刀效果很好:
In our MVC 5 project we use Angular. The following Razor works nicely:
@Html.EditorFor(x => x.FirstName,
new { required = "required", ng_model = "FirstName" })
但是,如果在呈现页面时将MVC Model.FirstName 设置为"Bob",则输入"字段仍为空白.
However, if the MVC Model.FirstName is set to "Bob" when the page is rendered, the Input field is still blank.
如果我在Angular控制器中进行了设置:
If I set this in the Angular controller:
$scope.FirstName = "@(Model.FirstName)";
然后出现鲍勃".
我的问题是:是否必须为UI中的每个字段设置 $ scope.VARIABLE = MODEL.VARIABLE ,还是我可以告诉Angular尊重ASP.NET MVC的内容?
My question is: Do I have to set the $scope.VARIABLE=MODEL.VARIABLE for every field in the UI, or can I tell Angular to respect what came over from ASP.NET MVC.
Angular似乎覆盖了MVC编写的[input value ="Bob"].
Angular is appearing to over write the [input value="Bob"] that MVC writes.
推荐答案
绑定到范围时,无需将模型分为单独的字段.相反,您应该绑定整个模型:
There is no need to separate the model into individual fields when you bind to scope. Instead you should bind the entire model:
$scope.model = @Html.Raw(Json.Encode(Model));
这将呈现给客户端:
$scope.model = { FirstName: 'John', LastName:'Doe', etc };
然后,您可以将输入字段绑定为:
Then you can bind your input fields as:
@Html.EditorFor(x => x.FirstName,
new { required = "required", ng_model = "model.FirstName" })
就个人而言,我认为它的清除程序不使用@Html,而是使用简单的HTML:
Personally, I think its cleaner not to use @Html, in favor of simple HTML:
<input ng-model="model.FirstName" required />
在Angular中,您实际上不再需要ID.
In Angular, you don't really need an id anymore.
这篇关于角ASP.NET MVC绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!