angularjs post data to mvc controller - asp.net-mvc

I have simple code using angularjs,
$http.post(postToCreateURL, addingProducts, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
})
.error(function () {
});
And I want bind this data to this Mvc controller
[HttpPost]
public JsonResult Create(ProductModel model)
{
NorthwindEntities db = new NorthwindEntities();
var products = db.Products.Select(s => new ProductModel
{
ProductName = s.ProductName,
SupplierID = s.SupplierID,
CategoryID = s.CategoryID,
QuantityPerUnit = s.QuantityPerUnit,
UnitPrice = s.UnitPrice,
UnitsInStock = s.UnitsInStock,
UnitsOnOrder = s.UnitsOnOrder,
ReorderLevel = s.ReorderLevel,
Discontinued = s.Discontinued
}).Take(5).ToList();
return Json(products, JsonRequestBehavior.AllowGet);
}
In this situation I'm getting null values. Thanks in advance!

Try this:
var request = {
ProductName: 'aa',
SupplierID: 'aa',
CategoryID: 'aa',
...
Discontinued: 'zzz'
}
$http.post(" URL IN HERE ", JSON.stringify(request), {
headers: {
'Content-Type': 'application/json'
}
})

Related

JSON object to ASP.NET MVC

I know there are multiple threads around this issue, but I still can't figure mine out. Can someone please help me figure out why my classObject always has null value? I feel like I've tried everything by now.
My class:
public class ClassAB
{
[Required]
[MaxLength(100)]
[DataType(DataType.Text)]
public string A{ get; set; }
[Required]
[MaxLength(100)]
[DataType(DataType.MultilineText)]
public string B{ get; set; }
}
My home controller:
[HttpPost]
public ActionResult MyMethod(ClassAB classObject)
{}
and my Javacript call
let data = {
"A": "A",
"B": "B"
}
await fetch(`https://localhost:44359/Home/MyMethod/`, {
method: "POST",
body: JSON.stringify(data),
contentType:"application/json",
success: (result)=>{
console.log(result)
},
failure: (result) => {
alert(result)
}
});
Found the issue. My contentType should have been in header. Modifying request to
await fetch(`https://localhost:44359/Home/MyMethod/`, {
method: "POST",
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
},
success: (result)=>{
console.log(result)
},
failure: (result) => {
alert(result)
}
});
fixed the issue
Try this
var data = [{A: 'A',B:'B'}];
await fetch(`https://localhost:44359/Home/MyMethod/`, {
method: "POST",
body: JSON.stringify(data),
contentType:"application/json",
success: (result)=>{
console.log(result)
},
failure: (result) => {
alert(result)
}
});
[HttpPost]
public ActionResult MyMethod(List<ClassAB > classObject)
{}
WebAPI won't know to model bind an object like that. See https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1
Try using the [FromBody] attribute
[HttpPost]
public ActionResult MyMethod([FromBody] ClassAB classObject)
{}
When combining this with a proper javascript post this will work, see image.
Sample js
<script>
var xhr = new XMLHttpRequest();
var url = "https://localhost:5001/api/default/MyMethod";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({ "A": "A", "B": "B" });
xhr.send(data);
</script>

Why my post dall does not get data in MVC and Angular 7

i have below code i want to post data from angular to Asp.net MVC but in object its null. method was call but parameter was null any idea why ??
ANGULAR
var result = { SearchText: "PARK"};
this.httpClient.post(
'http://localhost:55063/Common/PostAddress',result
).subscribe((res: any[]) => {
console.log(res);
this.data = res;
});
MVC
public class CommonController : Controller
{
protected SCommon sCommon = null;
public async Task<ActionResult> PostAddress(RoleModel Id)
{
sCommon = new SCommon();
var User = await sCommon.GetAddress(Id.SearchText).ConfigureAwait(false);
return Json(User, JsonRequestBehavior.AllowGet);
}
}
public class RoleModel
{
public string SearchText { get; set; }
}
try adding header to your post and stringify your body
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
};
var result = { SearchText: "PARK"};
const body = JSON.stringify(result);
this.httpClient.post('http://localhost:55063/Common/PostAddress',body,httpOptions).subscribe((res: any[]) => {
console.log(res);
this.data = res;
});
aslo enable cors like this in your Register method
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Angular 2 - web api : not get the posted data at api

From the page i am sending data:
register() {
this.loading = true;
this.Register = { firstName: 'aa', lastName: 'aa', email: 'aa', password: 'aa', cpassword: 'aa', gender: "male", dob: '2017-05-02' };
this.userService.create(this.Register)
.subscribe(
data => {
alert("aa");
},
error => {
// this.alertService.error(error);
this.loading = false;
});
}
I posted my data from Angular 2 service code is as below:
create(UserRegister: UserRegister) {
return this.http.post('http://localhost:53625/api/UserLoginAPI/InsertUser', UserRegister, this.jwt()).map((response: Response) => response.json());
}
private jwt() {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
return new RequestOptions({ headers: headers });
}
for this i write code in the api is as below:
[HttpPost]
public IHttpActionResult InsertUser(UserRegisterModel UserRegister)
{
int returnval = 0;
returnval = objUserLoginBAL.InsertUser(objUserRegisterModel);
return Json(returnval);
}
i get the call at api side but my object not get any value. that is shown in image:
I think the issue is your header construction. Try change this:
'Content-Type': 'application/x-www-form-urlencoded'
to this:
'Content-Type': 'application/json'
Also introduce a field for cpassword in UserRegisterModel.
Try below:
create(UserRegister: UserRegister) {
return this.http.post('http://localhost:53625/api/UserLoginAPI/InsertUser', UserRegister, this.jwt(UserRegister)).map((response: Response) => response.json());
}
private jwt(UserRegister: UserRegister) {
let _body = JSON.stringify(UserRegister);
let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });
return new RequestOptions({
headers: headers,
body: _body });
}
Your initial page should look like this: Notice I removed the cpassword as it's not in your API Model
register() {
this.loading = true;
this.Register = {
dob: '2017-05-02'
email: 'aa',
firstName: 'aa',
gender: "male",
lastName: 'aa',
password: 'aa',
};
this.userService.create(this.Register)
.subscribe((data:any) => {
alert("aa");
},(error:any) => {
// this.alertService.error(error);
this.loading = false;
});
}
Your Service: I cleaned up the jwt() function.
import { Http, Response, Headers, RequestOptionsArgs} from '#angular/http';
create(userRegister: UserRegister) {
let url:string = 'http://localhost:53625/api/UserLoginAPI/InsertUser';
return this.http.post(url, userRegister, this.jwt())
.map((res:Response) => res.json());
}
private jwt():RequestOptionsArgs {
let headers:Headers = new headers();
headers.append('Content-Type', 'application/json');
let options:RequestOptionsArgs = new RequestOptions();
options.headers = headers;
return options;
}

String instead of data

I'm trying to get data from the controller
something like this:
public IEnumerable<Custom> Search(string searchText = "")
{
return new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };
}
But angular gives me this
m
u
s
i
c
p
o
r
t
a
l
.
C
o
n
t
r
o
l
l
e
r
s
.
C
u
s
t
o
m
[
]
I tried add http.headers but nothing.
My code:
var musicportal = angular.module('musicportal', []);
musicportal.controller('SearchController', ['$scope', '$http', function ($scope, $http) {
$scope.answer = "awesome";
$scope.search = function (text) {
$scope.answer = text;
$scope.pms = [];
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = data;
});
$scope.searchText = "";
}
}]);
You should return data as json e.g.
public ActionResult Search(string searchText = "")
{
return Json(new { Foo = "Hello" }, JsonRequestBehavior.AllowGet);
}
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = data.Foo;
});
Now, in your case, you have a list, so you need to convert that into JSON. You can do that in ASP.NET MVC using JsonSerializer e.g.
public ActionResult Search(string searchText = "")
{
string json = "";
var items = new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };
using (var writer = new StringWriter())
using (var jsonWriter = new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, items);
json = writer.ToString();
}
return Json(json, JsonRequestBehavior.AllowGet);
}
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = JSON.Parse(data);
});
You may need to play about with this code, it's not perfect first time, but hopefully it will give you a head start.

Why Breeze jquery Where/Take/Order dont work in BreezeJs without nodb,

Here is my code:
Server-Web API
=======================================
public class OwnerDto {
public int OwnerId { set; get; }
public string OwnerName { set; get; }
}
[HttpGet]
public IEnumerable GetOwner()
{
IEnumerable result = new[] {
new OwnerDto { OwnerId = 1, OwnerName = "Test1" },
new OwnerDto { OwnerId = 2, OwnerName = "Test2" },
new OwnerDto { OwnerId = 3, OwnerName = "Test3" },
new OwnerDto { OwnerId = 4, OwnerName = "Test4" }
};
return result;
}
js code
var dataService = new breeze.DataService({
serviceName: "/api/owner/",
hasServerMetadata: false,
});
var manager = new breeze.EntityManager({ dataService: dataService });
var store = manager.metadataStore;
//metadataStore.namingConvention = namingConv;
store.addEntityType({
shortName: "Owner",
namespace: "Test.Owner",
dataProperties: {
OwnerId: { dataType: breeze.DataType.Int32, isPartOfKey: true },
OwnerName: { dataType: breeze.DataType.String}
}
});
var op = breeze.FilterQueryOp;
var query = new breeze.EntityQuery()
.from("GetOwner")
.where("ownerId",op.Equals,2);
manager.executeQuery(query).then(function (data) {
ko.applyBindings(data, $("#SearchResult")[0]);
}).fail(function (e) {
alert(e);
});
Html Code
p- data-bind="visible: !results" Fetching data ..
ul- data-bind="foreach: results, visible: results" style="display:none"
span- data-bind="text: OwnerName"
span- data-bind="text: OwnerId"
==========================================
The problem is all the data can display but the filter(where/take/order...) does not work.
Any ideas, Thanks very much!
I believe the reason is that the method on your query returns IEnumerable. Those verbs (where/take/order) only apply to service endpoints that return IQueryable<T>. Try this:
[HttpGet]
public IQueryable GetOwner()
{
IEnumerable result = new[] {
new OwnerDto { OwnerId = 1, OwnerName = "Test1" },
new OwnerDto { OwnerId = 2, OwnerName = "Test2" },
new OwnerDto { OwnerId = 3, OwnerName = "Test3" },
new OwnerDto { OwnerId = 4, OwnerName = "Test4" }
};
return result.AsQueryable();
}

Resources