Converting Json Post Back Data To XML - c#

This is my first web app project. I am using VS community, asp.net, bootstrap 4, C# and JS knockout for my view model, the server side data is coming from the company ERP SQL database using Entity Framework.
The idea is that the user receives a list of items to approve from the Company ERP system, which are loaded into the View Model. The View Model is structured as a JS Knockout observable array and that each item is a JS knockout item of observables (see full code below)
Once the user has processed the items as desired, I want the web app to post back the whole View Modal as a Json object and for the server Post Controller to take this Json object convert it to xml to send into a SQL stored procedure for insertion into the SQL database, from the SQL database the data will be handled and inserted into the ERP database
When I try to action the Post I get a 405 "Method Not Allowed"
> "tags": {
"ai.cloud.roleInstance": "[MYCOMPUTER].local",
"ai.operation.id": "c07680cd8c845240a9e3791018c39521",
"ai.operation.name": "POST ReqsTests",
"ai.location.ip": "::1",
"ai.internal.sdkVersion": "web:2.8.0-241",
"ai.internal.nodeName": "[MYCOMPUTER].local"
},
"data": {
"baseType": "RequestData",
"baseData": {
"ver": 2,
"id": "|c07680cd8c845240a9e3791018c39521.66f8d951_",
"name": "POST ReqsTests",
"duration": "00:00:00.0279394",
"success": false,
"responseCode": "405",
"url": "http://localhost:64234/api/ReqsTests/",
"properties": {
"DeveloperMode": "true",
"_MS.ProcessedByMetricExtractors": "(Name:'Requests', Ver:'1.1')"
}
}
}
}
I think that I am not receiving the Json Date from the client correctly. My thinking is because I am sending the whole model back, which is a Json list, which but My controller does not receiver a List rather a string.
Can any one explain how my controller should receive the client side data
Here is my call to my Controller from the client and the server Post controller and full code listing is below
self.postAllReqs = function(self) {
self.error(''); // Clear error message
var data = ko.toJSON(self.Reqs); // convert to json
console.log(data);
ajaxHelper(reqsUri, 'POST', data).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
// POST: api/ReqsTests
public IHttpActionResult PostReqsTest(string json)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
try
{
//SQL store procedure
SqlParameter param1 = new SqlParameter("#XmlIn", doc);
db.Database.ExecuteSqlCommand("exec [CHC_Web].[TestWebHandShake],#XmlIn",
param1);
}
catch (Exception e)
{
string message = e.Message;
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message));
}
return Ok();
}
Thanks
View Model Code
function ReqsTest(rt) {
rt = rt || {};
var self = this;
self.id = ko.observable(rt.ID || 0);
self.requisition = ko.observable(rt.Requisition || "");
self.reqnStatus = ko.observable(rt.ReqnStatus || "");
self.dateReqnRaised = ko.observable(rt.DateReqnRaised|| null);
self.reqnValue = ko.observable(rt.ReqnValue || null);
self.approvedValue = ko.observable(rt.ApprovedValue || null);
self.originator = ko.observable(rt.Originator || "");
self.origName = ko.observable(rt.OrigName || "");
self.origEmail = ko.observable(rt.OrigEmail || "");
self.line = ko.observable(rt.Line || 0.00);
self.indx = ko.observable(rt.INDX || 0);
self.dateReqnRaisedL = ko.observable(rt.DateReqnRaisedL || null);
self.reqStatus = ko.observable(rt.ReqStatus || "");
//self.reqBackground = ko.observable(rt.ReqBackground || "");
//Computed observables
self.reqBackground = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "card-heading bg-success text-white"; }
else if (status == "D") { return "card heading bg-secondary"; }
else if (status == "R") { return "card heading bg-warning"; }
else if (status == "E") { return "card heading bg-danger"; }
else {
return "card-heading bg-primary text-white";
}
})
self.reqStatusLabel = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "Approved"; }
else if (status == "D") { return "Declined - put on hold"; }
else if (status == "R") { return "Routing On"; }
else if (status == "E") { return "Erase On Syspro"; }
else {
return "Awaiting Approval";
}
})
self.approvalBtn = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "css: button btn-secondary "; }
else {
return "btn btn-success ";
}
})
self.approvalBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "W") { return "Approve"; }
else {
return "UnApprove";
}
})
self.declineBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "D") { return "UnDecline"; }
else {
return "Decline";
}
})
self.deleteBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "E") { return "Restore"; }
else {
return "Erase";
}
})
// Functions
//show details alert
$(".btn").on("click", function () {
$(".alert").removeClass("in").show();
$(".alert").delay(200).addClass("in").fadeOut(2000);
});
}
function ReqsViewModel (){
var self = this;
self.Reqs = ko.observableArray([]);
self.error = ko.observable();
var reqsUri = '/api/ReqsTests/';
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllReqs() {
ajaxHelper(reqsUri, 'GET').done(function (data) {
// Build the ReqsTest objects
var reqs = ko.utils.arrayMap(data, function (rt) {
return new ReqsTest(rt);
});
self.Reqs(reqs);
});
}
self.postAllReqs = function(self) {
self.error(''); // Clear error message
var data = ko.toJSON(self.Reqs); // convert to json
console.log(data);
ajaxHelper(reqsUri, 'POST', data).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
// Details
self.detail = ko.observable();
self.getReqDetail = function (item) {
//var url = reqsUri + item.indx();
//ajaxHelper(url, 'GET').done(function (data) {
// self.detail(data);
//}
//);
self.detail(item)
}
//Approval function
self.Approval = function (item) {
var status = item.reqStatus();
if (status == "W") { item.reqStatus("A"); }
else
{ item.reqStatus("W"); }
self.getReqDetail(item);
}
//Decline function
self.Decline = function (item) {
var status = item.reqStatus();
if (status == "D") { item.reqStatus("W"); }
else { item.reqStatus("D"); }
self.getReqDetail(item);
}
//Delete function
self.Delete = function (item) {
var status = item.reqStatus();
if (status == "E") { item.reqStatus("W"); }
else { item.reqStatus("E"); }
self.getReqDetail(item);
}
// Load the reqs - Take this out if you don't want it
getAllReqs();
}
ko.applyBindings(new ReqsViewModel());
Model Class
namespace POC_Reqs_v1.Models
{
using System;
using System.Collections.Generic;
public partial class ReqsTest
{
public string ID { get; set; }
public string Requisition { get; set; }
public string ReqnStatus { get; set; }
public Nullable<System.DateTime> DateReqnRaised { get; set; }
public Nullable<decimal> ReqnValue { get; set; }
public Nullable<decimal> ApprovedValue { get; set; }
public string Originator { get; set; }
public string OrigName { get; set; }
public string OrigEmail { get; set; }
public decimal Line { get; set; }
public long INDX { get; set; }
public string DateReqnRaisedL { get; set; }
public string ReqStatus { get; set; }
public string ReqBackground { get; set; }
}
}
Controller Code
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml;
using Newtonsoft.Json;
using POC_Reqs_v1.Models;
namespace POC_Reqs_v1.Controllers
{
public class ReqsTestsController : ApiController
{
private ChamberlinWebEntities db = new ChamberlinWebEntities();
// GET: api/ReqsTests
public IQueryable<ReqsTest> GetReqsTests()
{
return db.ReqsTests;
}
// GET: api/ReqsTests/5
[ResponseType(typeof(ReqsTest))]
public async Task<IHttpActionResult> GetReqsTest(string id)
{
var ID = Convert.ToInt64(id);
ReqsTest reqsTest = await db.ReqsTests.FindAsync(ID);
if (reqsTest == null)
{
return NotFound();
}
return Ok(reqsTest);
}
// PUT: api/ReqsTests/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutReqsTest(string id, ReqsTest reqsTest)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != reqsTest.ID)
{
return BadRequest();
}
db.Entry(reqsTest).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ReqsTestExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/ReqsTests
public IHttpActionResult PostReqsTest(string json)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
try
{
//SQL store procedure
SqlParameter param1 = new SqlParameter("#XmlIn", doc);
db.Database.ExecuteSqlCommand("exec [CHC_Web].[TestWebHandShake],#XmlIn",
param1);
}
catch (Exception e)
{
string message = e.Message;
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message));
}
return Ok();
}
// DELETE: api/ReqsTests/5
[ResponseType(typeof(ReqsTest))]
public async Task<IHttpActionResult> DeleteReqsTest(string id)
{
ReqsTest reqsTest = await db.ReqsTests.FindAsync(id);
if (reqsTest == null)
{
return NotFound();
}
db.ReqsTests.Remove(reqsTest);
await db.SaveChangesAsync();
return Ok(reqsTest);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ReqsTestExists(string id)
{
return db.ReqsTests.Count(e => e.ID == id) > 0;
}
}
}

For completeness here was my final solution:
The main problem was the syntax error in the post controller, which did not create an error when compiled, the line that was incorrect was
// POST: api/ReqsTests
public IHttpActionResult PostReqsTest(string json)
The correct syntax was in the end
public async Task<IHttpActionResult> PostReqsTest(object json)
So the full controller code is was
// POST: api/ReqsTests
public async Task<IHttpActionResult> PostReqsTest(object json)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//convert the Json model to xml
XmlDocument doc = JsonConvert.DeserializeXmlNode(json.ToString());
try
{
//SQL store procedure
SqlParameter param1 = new SqlParameter("#XmlIn", doc.InnerXml);
db.Database.ExecuteSqlCommand("exec [CHC_Web].[TestWebHandShake] #XmlIn",
param1);
}
catch (Exception e)
{
string message = e.Message;
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message));
}
return ResponseMessage(Request.CreateResponse HttpStatusCode.OK,"Inserted to database")); }

Related

I am getting Error 415 while uploading image in Angular and .Net core project

I want to upload an image to my project, but unfortunately it gives an error of 415. Swagger does not give an error when I install it from above, but it gives an error when I install it from above Angular. What is the solution to this?
Backend Web Api Code;
[Produces("application/json", "text/plain")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(string))]
[HttpPost("update")]
public async Task<IActionResult> Update([FromFrom] UpdatePresidentMessageCommand updatePresidentMessage)
{
var result = await Mediator.Send(updatePresidentMessage);
if (result.Success)
{
return Ok(result.Message);
}
return BadRequest(result.Message);
}
}
Backend Handlers Code;
if (request.Image != null)
{
var fileUpload = Core.Extensions.FileExtension.FileUpload(request.Image, fileType: Core.Enums.FileType.Image);
if (fileUpload != null)
{
isTherePresidentMessageRecord.Image = fileUpload.Path;
}
}
Angular Service Code;
updatePresidentMessage(presidentMessage: FormData): Observable<any> {
return this.httpClient.post('https://localhost:60021/Admin/api' + '/presidentMessages/update', presidentMessage,{ responseType: 'text' });
}
Angular Ts Code;
update(): void {
let presidentModel = Object.assign({}, this.presidentMessageFormGroup.value);
const formData = new FormData();
formData.append('id', presidentModel.id.toString());
formData.append('shortDescription', presidentModel.shortDescription);
formData.append('description', presidentModel.description);
for (const photo of this.photos) {
formData.append('image', photo, photo.name);
}
this.presidentMessageService.updatePresidentMessage(formData).subscribe(response => {
this.alertifyService.success(response);
});
}
onFileSelect(event: any) {
if (event.target.files.length > 0) {
for (const file of event.target.files) {
this.photos.push(file);
}
}
}
" const headers = new HttpHeaders().set('Content-Type', 'multipart/form-data');
" the error I get when I add;
enter image description here
UpdatePresidentMessageCommand Class;
public int ID { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public IFormFile Image { get; set; }
public class UpdatePresidentMessageCommandHandler : IRequestHandler<UpdatePresidentMessageCommand, IResult>
{
private readonly IPresidentMessageRepository presidentMessageRepository;
private readonly IUserService userService;
public UpdatePresidentMessageCommandHandler(IUserService userService, IPresidentMessageRepository presidentMessageRepository)
{
this.userService = userService;
this.presidentMessageRepository = presidentMessageRepository;
}
[LogAspect(typeof(FileLogger))]
[SecuredOperation(Priority = 1)]
public async Task<IResult> Handle(UpdatePresidentMessageCommand request, CancellationToken cancellationToken)
{
var isTherePresidentMessageRecord = await this.presidentMessageRepository.GetAsync(u => u.ID == request.ID);
if (isTherePresidentMessageRecord == null)
{
return new ErrorResult(message: Messages.Error);
}
isTherePresidentMessageRecord.ShortDescription = request.ShortDescription;
isTherePresidentMessageRecord.Description = request.Description;
isTherePresidentMessageRecord.UpdateByUserID = this.userService.GetNameIdentifier();
isTherePresidentMessageRecord.UpdateDateTime = System.DateTime.Now;
if (request.Image != null)
{
var fileUpload = Core.Extensions.FileExtension.FileUpload(request.Image, fileType: Core.Enums.FileType.Image);
if (fileUpload != null)
{
isTherePresidentMessageRecord.Image = fileUpload.Path;
}
}
this.presidentMessageRepository.Update(isTherePresidentMessageRecord);
await this.presidentMessageRepository.SaveChangesAsync();
return new SuccessResult(Messages.Updated);
}
}
Try to set the correct 'Content-Type' on the header of your POST request.

How to determine which method is used, using my custom attribute in ASP.NET Core

Hi guys i am finding solution, how can i get the specific method that uses my custom attribute and also i am using generic to get the specific class
this is my abstract class in my that inherited to my controller:
public abstract class BaseController<T> : ControllerBase
{
protected string Role
{
get
{
return GetCustomerRole(typeof(T));
}
set { }
}
private string GetCustomerRole(Type t)
{
string role = string.Empty;
var pfRole = Attribute.GetCustomAttribute(t, typeof(PFRole)) as PFRole;
if (pfRole != null)
{
role = pfRole.Role;
}
MemberInfo[] MyMemberInfo = t.GetMethods();
for (int i = 0; i < MyMemberInfo.Length; i++)
{
pfRole= Attribute.GetCustomAttribute(MyMemberInfo[i], typeof(PFRole)) as PFRole;
if (pfRole != null)
{
role = pfRole.Role;
}
}
return role;
}
and this one is my controller:
[PFRole(Role="Admin")]
public class CryptoController: BaseController<CryptoController>
{
// some contructor and DI Services
[PFRole(Role="Customer")]
[HttpGet]
[Route("price/list")]
public async Task<ActionResult> GetPriceList()
{
try
{
if (_Principal != null)
{
if (VerifyTokenRole)
{
return Ok(await _cryptoCompareService.GetPrices());
}
return BadRequest(new { success = false, msg = "Oops, you are not authorize to access this page" });
}
return BadRequest(new { success = false, msg = "Invalid Token" });
}
catch(Exception e)
{
_logger.LogError(e.Message);
_logger.LogTrace(e.StackTrace);
}
return BadRequest(new { success = false, msg = "Unknown Error occured. Please try again." });
}
[PFRole(Role="admin")]
[HttpGet]
[Route("last-price")]
public async Task<ActionResult> GetCoinLastPrice()
{
try
{
if (_Principal != null)
{
if (VerifyTokenRole)
{
return Ok(await _cryptoCompareService.GetCoinLastPrice());
}
return BadRequest(new { success = false, msg = "Oops, you are not authorize to access this page" });
}
return BadRequest(new { success = false, msg = "Invalid Token" });
}
catch (Exception e)
{
_logger.LogError(e.Message);
_logger.LogTrace(e.StackTrace);
}
return BadRequest(new { success = false, msg = "Unknown Error occured. Please try again." });
}
this is my custom attribute:
public class PFRole: Attribute
{
// customer by default
public string Role;
public PFRole()
{
Role = "Customer";
}
}
now, how can i get the method that uses this custom attribute?

(.NET Core Api) What is the difference between passing an object and passing a parameter to an action?

I have a .NET Core web API with crud functions
when I pass an object like (Product obj) as json serialization to an action, its value arrive to the action well as you can see here...
But, when I pass a parameter like (int id) as json serialization, the value not arrive to the action as you can see here
the only way is to pass the parameter as Query String like ?id=5, in this case the value arrive to the action as you can see here
Now, I need to pass parameter as json, so...
What is the difference between this 2 cases (json & query string)??
How could I pass parameter as json and not as query string??
this is controller code
private readonly IProductRep rep;
public ProductController(IProductRep rep)
{
this.rep = rep;
}
[EnableCors("allow")]
[HttpPost]
public IActionResult GetAllProducts()
{
try
{
return Json(new { Result = "OK", Records = rep.GetAllProducts() });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public JsonResult AddNewProduct(Product obj)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
Product product = rep.AddNewProduct(obj);
return Json(new { Result = "OK", Record = product });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public JsonResult GetProductById(int id)
{
try
{
return Json( new { Result = "OK", Records = rep.GetProductById(id) });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public IActionResult DeleteProduct(int id)
{
try
{
rep.DeleteProduct(id);
return Json( new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public JsonResult EditProduct(Product obj)
{
try
{
return Json( new { Result = "OK", Records = rep.EditProduct(obj) });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
This is my client-side code (I'm using jtable)
$('#container').jtable({
title: 'Table of people',
actions: {
listAction:'http://localhost:62881/product/GetAllProducts',
createAction:'http://localhost:62881/product/AddNewProduct',
updateAction: 'http://localhost:62881/product/EditProduct',
deleteAction: 'http://localhost:62881/product/DeleteProduct'
},
fields: {
Id: {
key: true,
create:false,
edit:false,
list: true
},
ProductName: {
title: 'Name',
width: '40%'
},
Price: {
title: 'Price',
width: '20%'
},
ProductCode: {
title: 'Product Code',
width: '30%'
}
}
});
$('#container').jtable('load');
this is what happened with postman when trying to send id as json
but when I add id as a paramerter in routing and send it as querystring it works as you can see here
For the first call you can make something like this:
public JsonResult AddNewProduct([FromBody]Product obj)
I think you can add an attribute like this
[HttpGet("api/GetProductById/{id}")]
public JsonResult GetProductById(int id)
this way you don't have to make a call like ?id=5
Hope this helps...
In c#, int is primitive data type (stores in stack & not in heap) and it is not an object. Hence, JsonSeriallizer can not serialize your id if its only int. Read about this here: https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
Though, if you want to pass id as json and not as query string, you can wrap this id within a class and you can serialize that object and can pass it through that. refer below example.
[Route("api/[controller]")]
public class PersonController : Controller
{
public string Get([FromQuery] GetPersonQueryObject request)
{
// Your code goes here
}
}
public class GetPersonQueryObject
{
public int? Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
}
I would suggest if you just needs to retrieve the data from API, then should use GET http call. Also, GET is less secure compared to POST because data sent is part of the URL & Data is visible to everyone in the URL.

Getting the result from controller but ajax call fetching error instead of success in MVC5 and C#

The controller is giving me the result and TempData["DCFormList"] is showing the count 3 (key, value and success message) but in the AJAX call I am getting alert("fail").
public ActionResult INTImportData()
{
if (Session["UserLogon"] != null)
{
BLINTForms objForm = new BLINTForms();
objDCFormList = new DCFormList();
int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
ViewBag.jobId = jobId;
objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
TempData["DCFormList"] = objDCFormList.Form;
return View(objDCFormList.Form);
}
else
return Redirect("~/Account/Login");
}
function GetINTFormTempData(JobId) {
var result = null;
$.ajax({
type: "GET",
url: '/ImportForms/GetINTFormTempDataByJobId',
data: { jobId: JobId },
traditional: false,
success: function (data)
{
result = data;
alert ("JobId");
LoadINTData(result);
if (result.length > 0)
$(".upload").show();
else
$(".upload").hide();
},
error: function (data)
{
alert("fail");
Success = false;
}
});
public List<DCForm> GetINTFormTempDataByJobId(int jobId)
{
objDatabaseHelper = new DatabaseHelper();
List<DCForm> objDCFormList = new List<DCForm>();
DCForm objDCForm;
int record = 0;
try
{
objDatabaseHelper.AddParameter("Job_ID", jobId == 0 ? DBNull.Value : (object)jobId);
DbDataReader reader = objDatabaseHelper.ExecuteReader(BLDBRoutines.SP_GETINTFORMTEMPDATA, CommandType.StoredProcedure);
if (reader.HasRows)
{
while (reader.Read())
{
objDCForm = new DCForm();
objDCForm.SerialNo = ++record;
objDCForm.PayerId = reader.IsDBNull(reader.GetOrdinal("PayerId")) ? 0 : reader.GetInt32(reader.GetOrdinal("PayerId"));
objDCFormList.Add(objDCForm);
}
}
return objDCFormList;
}
catch (Exception exce)
{
throw exce;
}
finally
{
if (objDatabaseHelper != null)
objDatabaseHelper.Dispose();
}
}
public class DCForm : DataOperationResponse
{
public int SerialNo { get; set; }
public int PayerId { get; set; }
public class DCFormList : DataOperationResponse
{
private List<DCForm> _form = null;
public DCFormList()
{
if (_form == null)
_form = new List<DCForm>();
}
public List<DCForm> Form
{
get { return _form; }
set { _form = value; }
}
}
I have just tried to reproduce your case. Here are sample code. You can update your code to get from Database from my code.
Your controller:
public class ImportFormsController : Controller
{
public JsonResult INTImportData(int jobId)
{
//if (Session["UserLogon"] != null)
//{
BLINTForms objForm = new BLINTForms();
var objDCFormList = new DCForm.DCFormList();
//int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
//ViewBag.jobId = jobId;
objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
//TempData["DCFormList"] = objDCFormList.Form;
//Response.StatusCode = (int)HttpStatusCode.OK;
return Json(objDCFormList.Form, JsonRequestBehavior.AllowGet);
//}
//else
//return Json("Login required", JsonRequestBehavior.AllowGet);
}
}
public class BLINTForms
{
public List<DCForm> GetINTFormTempDataByJobId(int jobId)
{
List<DCForm> objDCFormList = new List<DCForm>();
DCForm objDCForm;
int record = 0;
try
{
for (var i = 0; i < 5; i++)
{
objDCForm = new DCForm();
objDCForm.SerialNo = ++record;
objDCForm.PayerId = 100;
objDCFormList.Add(objDCForm);
}
return objDCFormList;
}
catch (Exception exce)
{
throw exce;
}
finally
{
}
}
}
public class DCForm : DataOperationResponse
{
public int SerialNo { get; set; }
public int PayerId { get; set; }
public class DCFormList : DataOperationResponse
{
private List<DCForm> _form = null;
public DCFormList()
{
if (_form == null)
_form = new List<DCForm>();
}
public List<DCForm> Form
{
get { return _form; }
set { _form = value; }
}
}
}
public class DataOperationResponse
{
//public string Message { get; set; }
}
I create a test in HomeController:Index with Index.cshtml
<input type="text" id="jobId"/>
<button onclick="GetINTFormTempData($('#jobId').val())">Get Data</button>
<script>
function GetINTFormTempData(JobId) {
var result = null;
$.ajax({
type: "GET",
url: '/ImportForms/INTImportData', //**change url**
data: { jobId: JobId },
traditional: false,
success: function(data) {
result = data;
alert("JobId");
alert(JSON.stringify(data));
LoadINTData(result);
if (result.length > 0)
$(".upload").show();
else
$(".upload").hide();
},
error: function(data) {
alert("fail");
Success = false;
}
});
}
</script>
You should use this
Change ActionResult to JsonResult and
return Json(objDCFormList.Form, JsonRequestBehavior.AllowGet);
TempData["DCFormList"] can not get value in your AJAX call.
And also check your url in route with url in ajax call.
If I get your question correctly and, and if you want to use ActionResult set result as Success with:
Response.StatusCode = (int)HttpStatusCode.OK;
So in your case:
public ActionResult INTImportData()
{
if (Session["UserLogon"] != null)
{
BLINTForms objForm = new BLINTForms();
objDCFormList = new DCFormList();
int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
ViewBag.jobId = jobId;
objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
TempData["DCFormList"] = objDCFormList.Form;
Response.StatusCode = (int)HttpStatusCode.OK;
return View(objDCFormList.Form);
}
else
return Redirect("~/Account/Login");
}
I hope this helps.

Angular 6 with .net core model not binding

So I have been learning some .net core and I am building an API with it. Normally I would work with angular and send requests there.
I have the following angular snippet:
const BloclDTO = {
Period: value.YearFormControl + value.MonthFormControl + '00',
ValueBlock1: value.OnelFormControl,
ValueBlock2: value.TwolFormControl,
ValueBlock3: value.ThreelFormControl,
ValueBlock4: value.FourlFormControl,
ParamId: 1
}
Then there's the backend model for the same data:
public class MiddleDTO
{
public string Period { get; set; }
public double ValueBlock1 { get; set; }
public double ValueBlock2 { get; set; }
public double ValueBlock3 { get; set; }
public double ValueBlock4 { get; set; }
public int ParamId { get; set; }
}
And finally the method that should send it:
in HttpService
addData(param: any) {
console.log('is http service: ', param);
return this.HttpClient.post(`api/Data/AddValue`, { params: param });
}
in Component
this.http.addData(BloclDTO).subscribe(res => {
console.log('res add ', res);
});
in .net Core Controler
[HttpPost]
[Route("AddValue")]
public JsonResult AddValue([FromBody]MiddleDTO param)
{
if (param == null)
{
return Json(new { error = true, text = "param is null" });
}
return Json(param);
}
But i have empty data in controller.
Try this one:
[HttpPost]
[Route("AddValue")]
public IHttpActionResult AddValue([FromBody]MiddleDTO param)
{
if (param == null)
{
return InternalServerError(new Exception("param is null"));
}
return OK(param);
}
angular:
addData(param: any) {
let bodyString = JSON.stringify( param );
let headers = new HttpHeaders({ 'Content-Type': 'application/JSON' });
return this._http.post<any>('api/Data/AddValue', bodyString, { headers: headers });
}

Categories