如何使用 angularjs 执行 ASP.Net 保存
本文关键字:Net 保存 ASP 执行 何使用 angularjs | 更新日期: 2023-09-27 17:57:24
我正在尝试将数据保存到DB。代码隐藏中不会命中断点,也不会保存数据。我在控制台日志中看到的只是 - PASS : [object Object]
.我哪里错了。
默认值.aspx:
<div data-ng-controller="defaultCtrl">
Username
<input type="text" id="txtUsername" data-ng-model="AdminUser.Username" />
<br />
Password
<input type="text" id="txtPassword" data-ng-model="AdminUser.Password" />
<br />
<button type="submit" data-ng-click="AddUser(AdminUser)">Submit</button>
</div>
默认值.aspx.cs:.class:
public class AdminUser
{
public string Username { get; set; }
public string Password { get; set; }
}
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void AddUser(AdminUser adminUser)
{ --breakpoint set here but not hit
--code to save data
AdminUserDB.AddUser(adminUser);
}
默认按.js:
app.controller("defaultCtrl",["$scope","DefaultFactory",function ($scope,DefaultFactory){
$scope.AddUser = function (AdminUser) {
var promise = DefaultFactory.AddUser(AdminUser);
promise.then(function (success) {
console.log("PASS : " + success);
},
function (error) {
console.log("ERR : " + error);
})
}
}]);
默认工厂.js:
app.factory("DefaultFactory", ["$http", function ($http) {
var Factory = {};
//add new user
Factory.AddUser = function ($params) {
//console.log($params); -- i can see the object with the data in console.
return $http({
url: "http://localhost:49271/default.aspx/AddUser",
method: "GET", --when i put POST here, there is an error in console
data: $params
})
.success(function (data, status) {
})
.error(function (data, status) {
console.log("DATA : " + data);
console.log("STATUS : " + status);
});
};
return Factory;
}]);
如果您不想使用 WebApi,则可以将保存记录的代码转移到第二个.aspx文件(或 .ashx 处理程序文件,该文件仅包含一些 C# 代码,但没有 HTML 页面)并从那里进行保存。
return $http({
url: "http://localhost:49271/SaveRecord.ashx",
method: "POST",
data: $params
})
如果要将 JSON 数据发布到 .ashx 文件,可以使用 JSON.Net 将数据反序列化回 C# 记录...
public class SaveRecordHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Read in a JSON record which has been POSTED to a webpage,
// and turn it back into an object.
string jsonString = "";
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
YourDataClass oneQuestion = JsonConvert.DeserializeObject<YourDataClass>(jsonString);
希望这有帮助。