Submit form through existing API URL and get JSON response - c#

Im new to API,
Below is my scenario, Where i need help. My code may have many issues, kindly help me to learn this. :)
I have an existing API URL, and My objective is to POST request to that existing API URL while submitting a form and get below JSON response
{
"success": true,
"message": "GOOD",
"data": null
}
.cshtml code
#section Scripts {
<script type="text/javascript">
$("#form1").submit(function () {
var Serial = $.post('http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL', $('#form1').serialize())
.success(function () {
var path = Serial.getResponseHeader('Location');
var i = $('<a/>', { href: path, text: path });
$('#message').html(i);
})
.error(function () {
$('#message').html("Error for changes.");
});
return false;
});
</script>
}
<div>
<form Id="form1" method="post" action="http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL" enctype="application/x-www-form-urlencoded">
<asp:Panel ID="pnlGrid" runat="server" Visible="true">
<table>
<tr>
<td style="width: 25%; height: 30px">
<div>
<label for="name">Special Instruction:</label>
<asp:CheckBox ID="CheckBox1" runat="server" />
</div>
</td>
</tr>
<tr>
<td style="width: 25%; height: 30px">
<div>
<label for="name" style="display: block">Notes: </label>
<textarea style="display: block"></textarea>
</div>
</td>
</tr>
<tr>
<td style="width: 25%; height: 30px">
</br>
<div>
<input type="submit" value="Submit" />
#*<button style="width:fit-content" name="StartRequest" value="StartRequest">Start Request</button>*#
</div>
</td>
<th style="border:inherit">
</th>
</tr>
</table>
</asp:Panel>
</form>
</div>
CONTROLLER
using DocumentFormat.OpenXml.ExtendedProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebApplication9.Models;
namespace WebApplication9.Controllers
{
using WebApplication9.Models;
public class ChangesController : ApiController
{
static readonly Dictionary<Guid, Change> _changes = new Dictionary<Guid, Change>();
[HttpPost]
[ActionName("Code")]
public HttpResponseMessage PostComplex(Change change)
{
if(ModelState.IsValid && change != null)
{
change.Notes = HttpUtility.HtmlEncode(change.Notes);
var Id = Guid.NewGuid();
_changes[Id] = change;
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(change.Notes)
};
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { action = "type", Id = Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[ActionName("Decode")]
public HttpResponseMessage PostSimple([FromBody] string value)
{
if(value != null)
{
Change change = new Change()
{
Notes = HttpUtility.HtmlEncode(value)
};
var Id = Guid.NewGuid();
_changes[Id] = change ;
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(change.Notes)
};
response.Headers.Location = new Uri(Url.Link("DefaultApi", new {action = "type", Id=Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpGet]
public Change Notes(Guid Id)
{
Change change;
if(_changes.TryGetValue(Id, out change))
{
return change;
}
else
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace WebApplication9.Models
{
public class Change
{
public string Notes { get; set; }
}
}
Webapiconfig.cs
namespace WebApplication9
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
}
I TRIED : POST existing API URL through Submit button of a webform.
Expected to get below response :
{
"success": true,
"message": "GOOD",
"data": null
}
But getting below error message :

Hi #Guru you can add generic API response wrapper to return you response.
public class ServiceResponse<T>
/// <summary>
/// Generic wrapper for web api response.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ServiceResponse<T>
{
public T Data { get; set; }
public bool Success { get; set; } = true;
public string Message { get; set; } = null;
public string Error { get; set; } = null;
public List<string> ErrorMessages { get; set; } = null;
}
How to use it:
ServiceResponse<NoteModel> _response = new();
_response.Success = true;
_response.Data = NoteModel;
_response.Message = "Created";
return _response;
Here is an example for both HttpResponseMessage and IHttpActionResult. I have tested both and they work.
[HttpPost]
[ActionName("Code")]
public HttpResponseMessage PostComplex(SampleViewModel change)
{
if (ModelState.IsValid && change != null)
{
ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();
var newGuid = Guid.NewGuid().ToString();
change.Id = newGuid;
if (!string.IsNullOrWhiteSpace(change.Id))
{
// ...
_response.Data = change;
_response.Success = true;
_response.Message = "Created";
return Request.CreateResponse(_response);
}
// ...
_response.Data = change;
_response.Success = false;
_response.Message = "Failed";
return Request.CreateResponse(_response);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[ActionName("Code")]
public IHttpActionResult PostComplex2(SampleViewModel change)
{
if (ModelState.IsValid && change != null)
{
ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();
var newGuid = Guid.NewGuid().ToString();
change.Id = newGuid;
if (!string.IsNullOrWhiteSpace(change.Id))
{
// ...
_response.Data = change;
_response.Success = true;
_response.Message = "Created";
return Ok(_response);
}
// ...
_response.Data = change;
_response.Success = false;
_response.Message = "Failed";
return Ok(_response);
}
else
{
return BadRequest();
}
}
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
public string Id { get; set; }
//See here for list of answers
public string Answer { get; set; }
}
public class ServiceResponse<T>
{
public T Data { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public string Error { get; set; }
public List<string> ErrorMessages { get; set; }
}

Related

Assigning data to a PageModel property in ASP.NET Core

I have this property in my PageModel:
public List<string> PhonenumbersFromExcel { get; set; }
I want to show data imported from Excel in my view. How can I assign my data in order to show from controller.
My question is: How can I do this? and is there any other way to solve it?
Below you can see my controller:
public virtual async Task<IActionResult> ImportPhonenumbersFromExcel(Model model, IFormFile importexcelfile, int currentFestivalId)
{
var phonenumbersFromExcel = new List<string>();
try
{
if (importexcelfile != null && importexcelfile.Length > 0)
{
var result = await _importManager.ImportPhonenumbersFromXlsxAsync(importexcelfile.OpenReadStream());
foreach (var item in result.Distinct())
{
var validPhonenumber = "";
// ensure given phonenumber starts with 0
if (!item.StartsWith("0"))
{
string zeroAdded = "0" + item;
validPhonenumber += zeroAdded;
}
bool isValid = true;
if (!CommonHelper.IsValidMobile(validPhonenumber))
isValid = false;
if (!CommonHelper.IsValidPhoneNumber(validPhonenumber))
isValid = false;
if (isValid)
phonenumbersFromExcel.Add(validPhonenumber);
}
model.PhonenumbersFromExcel.AddRange(phonenumbersFromExcel);
}
_notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.Festival.Phonenumbers.Imported"));
return RedirectToAction("Edit", new { id = currentFestivalId });
}
catch (Exception em)
{
await _notificationService.ErrorNotificationAsync(em);
return RedirectToAction("Edit", new { id = currentFestivalId });
}
}
Do you want to read data from Excel and display it on the page? You can use ExcelDataReader.
I did a simple test, you can refer to it.
Install related Nuget packages: ExcelDataReader and System.Text.Encoding.CodePages.
Model:
public class Phonenumber
{
public List<string> PhonenumbersFromExcel { get; set; }
}
Controller:
public class PhonenumberController : Controller
{
[HttpGet]
public IActionResult Index(Phonenumber phonenumber = null)
{
phonenumber = phonenumber == null? new Phonenumber() : phonenumber;
return View(phonenumber);
}
[HttpPost]
public IActionResult Index(IFormFile excelFile, [FromServices] IHostingEnvironment hostingEnvironment)
{
//I created a folder called files under wwwroot
string fileName = $"{hostingEnvironment.WebRootPath}\\files\\{excelFile.FileName}";
using (FileStream fileStream = System.IO.File.Create(fileName))
{
excelFile.CopyTo(fileStream);
fileStream.Flush();
}
var phoneNumber = this.GetNumber(excelFile.FileName);
return View(phoneNumber);
}
private Phonenumber GetNumber(string fName)
{
Phonenumber phonenumberModel = new Phonenumber();
phonenumberModel.PhonenumbersFromExcel = new List<string>();
var fileName = $"{Directory.GetCurrentDirectory()}{#"\wwwroot\files"}" + "\\" + fName;
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read())
{
phonenumberModel.PhonenumbersFromExcel.Add(reader.GetValue(0).ToString());
}
}
}
return phonenumberModel;
}
}
View:
#model Project.Models.Phonenumber
<div>
<form asp-action="Index" method="post" enctype="multipart/form-data">
<input type="file" name="excelFile" />
<input type="submit" value="Import" />
</form>
#if (Model.PhonenumbersFromExcel !=null &&Model.PhonenumbersFromExcel.Count()>0)
{
<hr />
<table cellpadding="0" cellspacing="0" border="1" class="table">
#foreach (var phonenumber in Model.PhonenumbersFromExcel)
{
<tr>
<td>#phonenumber</td>
</tr>
}
</table>
}
</div>
Test Result:

How would i get the data from each event from a jsonResult with full calendar

I'm attempting to get event data (Title, date,etc) for an event when clicked but I can't figure out a way to do it since I add the data through the JSON result and full calendar javascript. If I cant, is there a better way to allow the backend razorpage to send data to the full calendar javascript?
backend
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using DynaHealth.Models;
using Microsoft.AspNetCore.Http;
namespace TeleHealthB.Pages
{
public class CalendarModel : PageModel
{
// public IndexModel(TeleHealthB.Models.HealthProjectContext context)
//{
// healthProject = context;
//}
[BindProperty]
public string Title { get; set; }
[BindProperty]
public string Doc { get; set; }
[BindProperty]
public string Pat { get; set; }
[BindProperty]
public string dec { get; set; }
[BindProperty]
public DateTime date { get; set; }
[BindProperty]
public JsonResult result { get; set; }
public string today = DateTime.Today.ToString();
public void OnGet()
{
// result = (JsonResult)OnGetEvents();
}
public class eventShow
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
//public string description { get; set; }
// public string patient { get; set; }
// public string doctor { get; set; }
}
private DynaHealth2Context db;
public CalendarModel(DynaHealth2Context _db)
{
db = _db;
}
public IActionResult OnGetEvents()
{
List<eventShow> events = new List<eventShow>();
eventShow show = new eventShow();
try
{
string x = HttpContext.Session.GetString("Username");
using (var context = new DynaHealth2Context())
{
var query = from st in context.Appointments
where st.PatientEmail == x.Trim() || st.ProviderEmail == x.Trim()
select st;
// foreach (var item in query.ToList())
// {
// show.id = item.Id;
// show.title = item.Title;
// show.description = item.Description;
// show.start = item.Start.ToString("MM/dd/yyyy");
//show.end = item.End.ToString("MM/dd/yyyy");
// events.Add(show);
// }
return new JsonResult(query.ToList());
}
}
catch { return null; }
}
public IActionResult OnGetADDEvent(string sub)
{
// using (var context = new HealthProjectContext())
{
try
{
//context.Schedules.Add(schedule);
return null;
}
catch { return null; };
}
}
// public onPost()
// {
// RedirectToPage("./Meeting");
// }
public IActionResult OnPostRemoveEvent(string sub)
{
// using (var context = new HealthProjectContext())
{
try
{
// context.Schedules.Add(schedule);
return null;
}
catch { return null; };
}
}
}
}
frontend
#model TeleHealthB.Pages.CalendarModel
#{
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Calendar</title>
<link href='~/lib/TestCalendar/main.css' rel='stylesheet' />
<script src='~/lib/TestCalendar/main.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
initialDate: Date.now(),
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
select: function (arg) {
var title = prompt('Reasining For meeting:');
if (title) {
var tie = prompt('Time');
}
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
Starttime: tie,
end: arg.end,
EndTime: arg.EndTime
})
}
calendar.unselect()
},
eventClick: function (event, jsEvent, view) {
window.open("/Meeting", "_blank");
return false
},
editable: false,
dayMaxEvents: true, // allow "more" link when too many events
events: "/calendar?handler=events"
});
calendar.render();
});
</script>
<style>
#calendar {
max-width: 1100px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>Schedule View</h1>
<div id='calendar'></div>
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="false">x</span>
<span class="sr-only">Close</span>
</button>
<h4 id="modalTItle" class="modal-title"> </h4>
</div>
<div id="modalBody" class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" name="del" class="btn btn-default" id="eventURL">Delete</button>
<a class="btn btn-primary" id="eventURL" target="_blank">Schedule</a>
</div>
</div>
</div>
</div>
</body>
</html>
}
If you want to get the event in the backend,you can do following change:
You can use code var events = calendar.getEvents(); to get all the events,and then push the property you want in the array,the pass the arry to the backend.
Frontend
//Add a button to get event:
<button id="GetEvent">Get Event</button>
//....
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
initialDate: Date.now(),
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
select: function (arg) {
var title = prompt('Reasining For meeting:');
if (title) {
var tie = prompt('Time');
}
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
Starttime: tie,
end: arg.end,
EndTime: arg.EndTime
})
}
calendar.unselect()
},
eventClick: function (event, jsEvent, view) {
window.open("/Meeting", "_blank");
return false
},
editable: false,
dayMaxEvents: true, // allow "more" link when too many events
events: "/calendar?handler=events"
});
calendar.render();
//add following
$("#GetEvent").click(function () {
var events = calendar.getEvents();
var e = [];
$.each(events, function (index, value) {
console.log(value.start);
console.log(index);
var start_time = value.start;
var end_time = value.end;
var id = parseInt(value.id);
var slot = {
start: start_time,
end: end_time,
id: id,
};
e.push(slot);
});
$.ajax({
url: '/test?handler=getevents',
contentType:"application/json",
data: JSON.stringify(e),
dataType: "json",
type: "POST",
});
});
});
Backend:
//add this line
[IgnoreAntiforgeryToken]
public class TestModel : PageModel
{
[BindProperty]
public string Title { get; set; }
[BindProperty]
public string Doc { get; set; }
[BindProperty]
public string Pat { get; set; }
[BindProperty]
public string dec { get; set; }
[BindProperty]
public DateTime date { get; set; }
//delete this line
//[BindProperty]
public JsonResult result { get; set; }
public string today = DateTime.Today.ToString();
public void OnGet()
{
JsonResult result = (JsonResult)OnGetEvents();
}
public class eventShow
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public IActionResult OnGetEvents()
{
}
public void OnPostGetEvents([FromBody]List<eventShow> model)
{
}
Test result:

Save jQuery JSON object into SQL table without creating View model class in MVC ASP.NET Core

I am working on reading JSON data from the URL and insert it into the SQL table. I have used this sample URL https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json and create a Model class file as below.
View Model Class
public class ApiJsonViewModel
{
public string Title { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public string Filename { get; set; }
public string Height { get; set; }
public string Width { get; set; }
public string Price { get; set; }
public string Rating { get; set; }
}
I have a form with one textbox control to display JSON key data from the third-party API URL and a drop-down list with values from the database.
The model class used to populate dropdownlist
public class K360DbCatgViewModel
{
public string Name { get; set; }
public string MetaTitle { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public decimal Price { get; set; }
public decimal? OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTimeOffset? SpecialPriceStart { get; set; }
public DateTimeOffset? SpecialPriceEnd { get; set; }
public int StockQuantity { get; set; }
public string Sku { get; set; }
public string Gtin { get; set; }
public string NormalizedName { get; set; }
public int DisplayOrder { get; set; }
public int ReviewsCount { get; set; }
public double? RatingAverage { get; set; }
}
Razor View Page
<table class="table" id="tb_properties" style="width:100%">
<tr>
#if (ViewBag.ApiProp != null)
{
#foreach (var itemApiProp in ViewBag.ApiProp)
{
<td>
<input type="text" value="#itemApiProp.Key" class="form-control" />
<select class="form-control">
<option value="">--Select-- </option>
#foreach (var itemK360Prop in ViewBag.K360Prop)
{
<option>#itemK360Prop.Key</option>
}
</select>
</td>
}
}
</tr>
<tr>
<td>
<button type="submit" class="btn btn-primary" style="margin-
right:50px">Catalog Mapping</button>
</td>
</tr>
</table>
Controller code to fetch values for the view controls
public IActionResult Index()
{
string strAPIUrl = "https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json";
string jsonUrlProducts;
using (WebClient client = new WebClient())
{
jsonUrlProducts = client.DownloadString(strAPIUrl);
}
CreateDynamicAPiProp(jsonUrlProducts);
CreateK360Prop();
return View();
}
[HttpGet]
public IActionResult CreateDynamicAPiProp(string ApiUrl)
{
Dictionary<string, object> dictResultsAdd = new Dictionary<string, object>();
var objResponseB = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(ApiUrl);
foreach (Dictionary<string, object> DictMainKV in objResponseB)
{
foreach (KeyValuePair<string, object> item in DictMainKV)
{
dictResultsAdd.Add(item.Key, item.Value);
}
break;
}
ViewBag.ApiProp = dictResultsAdd;
return RedirectToAction("Index");
}
[HttpGet]
public IActionResult CreateK360Prop()
{
var ListK360Prop = new List<ApiMapDbViewModel>();
PropertyInfo[] propertyInfosK360 = typeof(K360DbCatgViewModel).GetProperties();
foreach (PropertyInfo propertyInfoK360 in propertyInfosK360)
{
ListK360Prop.Add(new ApiMapDbViewModel{Value = propertyInfoK360.Name.ToString(), Key = propertyInfoK360.Name.ToString()});
}
ViewBag.K360Prop = ListK360Prop;
return RedirectToAction("Index");
}
I have used the below jQuery and passed the JSON Model object to controller insert method on HTTP post to save selected records.
jQuery Code
#section scripts{
<script>
$(function() {
$("button[type='submit']").click(function() {
event.preventDefault();
var properties = [];
$("#tb_properties tr:first").find("td").each(function(index, item) {
var propertyname = $(item).find("input[type='text']").val();
var selctedvalue = $(item).find("select").val();
properties.push('"' + propertyname + '":"' + selctedvalue + '"');
});
var jsonstr = '{' + properties.join(",") + '}';
var jsobject = JSON.parse(jsonstr);
$.ajax({
type: "Post",
url: "/KEMap/Insert",
data: {
jsonModel: jsobject
},
success: function(response) {
toastr.info(response.status + "<br>" + "<br>" + response.message);
$("#tb_properties select").val("");
$("#partial_div").load(window.location.href + " #partial_div");
},
error: function(xhr, textStatus, errorThrown) {
console.log('in error');
}
});
});
});
</script>
Insert Method
[HttpPost]
public IActionResult Insert(ApiJsonViewModel jsonModel)
{
Type type = jsonModel.GetType();
PropertyInfo[] props = type.GetProperties();
List<K360mapMaster> K360mapListObj = new List<K360mapMaster>();
K360mapListObj = props.Where(c => !string.IsNullOrEmpty(c.GetValue(jsonModel, null)?.ToString())).Select(c => new K360mapMaster()
{ClientCatalog = c.Name, K360catalog = c.GetValue(jsonModel, null)?.ToString()}).ToList();
if (K360mapListObj.Count > 0)
{
_context.K360mapMasters.AddRange(K360mapListObj);
_context.SaveChanges();
return Json(new { Status = "Sucess", Message = "Mapped" });
}
return Json(new { Status = "Fail", Message = "Not done" });
}
SQL Table
CREATE TABLE [dbo].[K360Map_Master](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ClientCatalog] [nvarchar](450) NOT NULL,
[K360Catalog] [nvarchar](450) NOT NULL,
[MapFlag] [bit] NOT NULL,
CONSTRAINT [PK_K360Map_Master] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Everything working fine. I was able to insert selected textbox and dropdown list values into the SQL table.
The problem is JSON data I am using from the third-party API URL differ dynamically. For example for the below 2 sample URLs, I need to create again 2 model class file.https://gist.githubusercontent.com/dpetersen/1237910/raw/6ceb2161f756d4b4d5c22754d1ed8d869249f186/product_grid.js
https://raw.githubusercontent.com/mdn/fetch-examples/master/fetch-json/products.json.
I get the feedback as hardcoded coding with static data. I was not permitted to create a separate model class for each URL.
I also don't know how to proceed without creating a model class file. I need to pass selected control values to the controller insert method without a JSON model object.
I hope anybody can help me here.
Here is a working demo you could follow:
Model:
public class ApiMapDbViewModel
{
public string Value { get; set; }
public string Key { get; set; }
}
public class K360mapMaster
{
public string ClientCatalog { get; set; }
public string K360catalog { get; set; }
}
public class K360DbCatgViewModel
{
public string AA { get; set; }
public string BB { get; set; }
public string CC { get; set; }
public string DD { get; set; }
}
View:
<table class="table" id="tb_properties" style="width:100%">
<tr>
#if (ViewBag.ApiProp != null)
{
#foreach (var itemApiProp in ViewBag.ApiProp)
{
<td>
<input type="text" value="#itemApiProp.Key" class="form-control" />
<select class="form-control">
<option value="">--Select-- </option>
#foreach (var itemK360Prop in ViewBag.K360Prop)
{
<option>#itemK360Prop.Key</option>
}
</select>
</td>
}
}
</tr>
<tr>
<td>
<button type="submit" class="btn btn-primary" style="margin-
right:50px">
Catalog Mapping
</button>
</td>
</tr>
</table>
JS(Add data: jsonstr,contentType:"application/json"):
#section scripts{
<script>
$(function () {
$("button[type='submit']").click(function () {
event.preventDefault();
var properties = [];
$("#tb_properties tr:first").find("td").each(function (index, item) {
var propertyname = $(item).find("input[type='text']").val();
var selctedvalue = $(item).find("select").val();
properties.push('"' + propertyname + '":"' + selctedvalue + '"');
});
var jsonstr = '{' + properties.join(",") + '}';
//var jsobject = JSON.parse(jsonstr);
$.ajax({
type: "Post",
url: "/KEMap/Insert",
//data: jsobject,
data: jsonstr,
contentType:"application/json",
success: function (response) {
toastr.info(response.status + "<br>" + "<br>" + response.message);
$("#tb_properties select").val("");
$("#partial_div").load(window.location.href + " #partial_div");
},
error: function (xhr, textStatus, errorThrown) {
console.log('in error');
}
});
});
});
</script>
}
Controller:
[HttpPost]
public IActionResult Insert([FromBody]JObject jsonModel)
{
Type type = jsonModel.GetType();
PropertyInfo[] props = type.GetProperties();
List<K360mapMaster> K360mapListObj = new List<K360mapMaster>();
foreach (JProperty prop in jsonModel.Children())
{
string key = prop.Name.ToString();
string value = prop.Value.ToString();
K360mapListObj.Add(new K360mapMaster() { ClientCatalog = key, K360catalog = value });
}
//do your stuff...
return Json(new { Status = "Fail", Message = "Not done" });
}
Note 1:
Because the mapped property in ApiJsonViewModel capitalize the first letter,so the data you get here ClientCatalog = c.Name, is capital.From my provided code,The code here string key = prop.Name.ToString(); get the json(https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json) key name which is lower case.If you want to keep the first letter capital,you could change the following line:
string key = prop.Name.ToString().First().ToString().ToUpper() + prop.Name.ToString().Substring(1);
Note 2:
If your project is asp.net core 3.x or asp.net 5,be sure your project has Newtonsoft support,otherwise,you cannot pass data to backend successfully.More details you could refer to:
.NET 5.0 MVC return Json is throwing a JSON Parser error
Result:

Call Web APi from MVC Project

I have created Web API using Oracle Database in C# ASP.NET MVC and ADO.NET Entity Model and everything works fine.
And right now, I need to create a another project which will call this API.
I create this because this Web API is a part of application and it will connect to another application.
I create a new MVC project and in my controller
public ActionResult GetAkontas()
{
IEnumerable<AkontasViewModel> akontas = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:57285/api/");
var responseTask = client.GetAsync("akontas");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = GetReadTask(result);
readTask.Wait();
akontas = readTask.Result;
}
else
{
//Error response received
akontas = Enumerable.Empty<AkontasViewModel>();
ModelState.AddModelError(string.Empty, "Server error try after some time.");
}
}
return View(akontas);
}
Here is the problem that I dont know how to call it API controller, do I need to have connection to server since I work with Oracle database ?
I create Model but not so sure do I need it however
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AkontasMVCWebApi.Models
{
public class AkontasViewModel
{
public string A_KONTO { get; set; }
public string NAZIV { get; set; }
public string SIFRA_RAD { get; set; }
public string OPSTINA { get; set; }
public string MB { get; set; }
public string ULICA { get; set; }
public string BROJ { get; set; }
public string PBROJ { get; set; }
public string MJESTO { get; set; }
public string PORESKI { get; set; }
public string TRANSAKCIJ { get; set; }
public string INTERNET { get; set; }
public string EMAIL { get; set; }
public string KONTAKT { get; set; }
public string TELEFON { get; set; }
public string FAKS { get; set; }
public DateTime? DAT_UNOS { get; set; }
public string PDVMB { get; set; }
public string VRSTA_KLIJENTA { get; set; }
public string DRZAVA { get; set; }
}
}
This is my first time to work with Oracle database and ADO.NET Entities and not so sure how to do this, create a Project which will call(use) my API
UPDATE
Here is my Web API project
Controller
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
namespace AkontasWebApi.Controllers
{
public class AkontasController : ApiController
{
//Ovo je objekat kojem se pristupa kroz bazu
public AkontasEntities db = new AkontasEntities();
// GET: api/Akontas
//Ovo je funkcija koja vraca Listu<> svih AKONTASA iz baze ne vezano po ID-u
[HttpGet]
[Route("api/Akontas")]
public IQueryable<AKONTA> GetAKONTAS()
{
return db.AKONTAS;
}
// GET: api/Akontas/5 -> ovo je routing tacnije putanja kako se koristi ova funkcija
//Ovo je funkcija koja vraca AKONTAS po ID-u
[HttpGet]
[ResponseType(typeof(AKONTA))]
public IHttpActionResult GetAKONTA(string id)
{
AKONTA aKONTA = db.AKONTAS.Find(id);
if (aKONTA == null)
{
return BadRequest("Ne postoji A_KONTO pod tim rednim brojem");
}
return Ok(aKONTA);
}
}
}
Index View
<br /><br />
<form>
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO" id='AkontasId'>
</div>
<div class="form-group">
<a class="btn btn-primary" id="aKonto" onClick='aKontoSubmit()'>Provjeri</a>
</div>
</form>
<script>
function aKontoSubmit() {
$.ajax({
type: "GET",
URL: "/api/Akontas/GetAKONTA",
data: { id: $('#AkontasId').val() },
contentType: "data/xml; charset=utf-8",
success: function (result) {
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
</script>
I can recommend some stuff to look out for:
1) Try using https in http://localhost:57285/api/. I've had a similar problem but not on IIS, I was using kestrel web server.
2) Try this after setting the base address and before GetAsync():
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Rating Record Is Not getting save in database

Controller=>>
view is sending data to SendRating and this method is responsible for storing data in database,,but data is not getting saved.
only authenticated user can rate ,but every time we faced rating failed..i can't understand what exactly the problem is.
public ActionResult SendRating(string r, string s, string id, string url)
{
try {
var context = new ApplicationDbContext();
string currentUserId = User.Identity.GetUserId();
int autoid = 0;
Int16 thisVote = 0;
Int16 O_ServID = 0;
Int16.TryParse(s, out O_ServID);
Int16.TryParse(r, out thisVote);
int.TryParse(id, out autoid);
if (!User.Identity.IsAuthenticated)
{
return Json("Not authenticated!");
}
switch (s)
{
case "5":
//var isIt = db.VoteModel.Where(v => v.O_ServID == O_ServID && v.UserId.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) && v.WorkerID == autoid).FirstOrDefault();
var service = context.OrderServices.Where(o => o.O_ServID == O_ServID).Single();
var worker = context.Workers.Where(w => w.WorkerID == autoid).Single();
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
var user = userManager.FindByName(User.Identity.Name);
VoteModel vm = new VoteModel()
{
Active = true,
//id
UserId = User.Identity.GetUserId(),
Votes = thisVote,
WorkerID = autoid,
O_ServID = O_ServID,
OrderServices = service,Workers = worker,User = user
};
var save = context.VoteModel.Add(vm);
if(db.SaveChanges() > 0)
{
HttpCookie cookie = new HttpCookie(url, "true");
Response.Cookies.Add(cookie);
return Json("<br />You rated " + r + " star(s), thanks !", JsonRequestBehavior.AllowGet);
}
// keep the school voting flag to stop voting by this member
//HttpCookie cookie = new HttpCookie(url, "true");
//Response.Cookies.Add(cookie);
//}
break;
default:
break;
}
return Json("Rating Failed!", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
HttpCookie cookie = new HttpCookie(url, "true");
Response.Cookies.Add(cookie);
return Json(ex.Message, JsonRequestBehavior.AllowGet);
throw;
}
}
public ActionResult VoteNow(int id, int serv)
{
ViewData["id"] = id;
ViewData["serv"] = serv;
return View();
}
public ActionResult VoteShow()
{
return View();
}
Model==>>
this is table schema where record has to be stored..
namespace WebApplication5.Models
{
public class VoteModel
{
[Key]
public int AutoId { get; set; }
public int O_ServID { get; set; }
public OrderService OrderServices { get; set; }
public int WorkerID { get; set; }
public Worker Workers { get; set; }
public Int16 Votes { get; set; }
public bool Active { get; set; }
[Required]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
}
}
view==>>
my view code is as follows...
sending data with json to controller with different parameters pass through ViewData[] ..
#{
ViewBag.Title = "VoteNow";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
<div id="page-wrapper">
<div id="page-inner">
<h2>VoteNow</h2>
#model string
#{
var url = Request.Url.AbsolutePath;
}
#if (Request.Cookies[url] == null)
{
<div id="ratingDiv" class="smallText">
Poor
<img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="1" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="2" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="3" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="4" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="5" /> Excellent
<label id="lblResult"></label>
</div>
<style type="text/css">
.ratingStar {
cursor: pointer;
height: 20px;
width: 20px;
}
</style>
}
else
{
<text><span style="color:green;"> Thanks for your vote !</span></text>
}
#section scripts{
<script type="text/javascript">
var clickedFlag = false;
$(".ratingStar").mouseover(function () {
$(this).attr("src", "/img/yellowstar.gif").prevAll("img.ratingStar").attr("src", "/img/yellowstar.gif");
});
$(".ratingStar, #radingDiv").mouseout(function () {
$(this).attr("src", "/img/whitestar.gif");
});
$("#ratingDiv").mouseout(function () {
if (!clickedFlag) {
$(".ratingStar").attr("src", "/img/whitestar.gif");
}
});
$(".ratingStar").click(function () {
clickedFlag = true;
$(".ratingStar").unbind("mouseout mouseover click").css("cursor", "default");
var url = "/CDashboard/SendRating?r=" + $(this).attr("data-value") + "&s=#((int)ViewData["serv"])&id=#((int)ViewData["id"])&url=#url";
$.post(url, null, function (data) {
$("#lblResult").html(data);
});
});
$("#lblResult").ajaxStart(function () {
$("#lblResult").html("Processing ....");
});
$("#lblResult").ajaxError(function () {
$("#lblResult").html("<br />Error occured.");
});
</script>
}
</div>
</div>

Categories