How to pass HTML(View) Table data to controller to save in slq table - asp.net-core

I am calculating the some values based on data available for previous month and displaying in table format in view. I have another model where I need to pass these values and save in database. I am not inputting any value, either values are static or calculated. Values are not passed from view to controller.
I have tried the jquery/ajax but not successful.
//Controller//
[HttpPost]
public JsonResult Proccess(List<ServerCount> deviceCounts)
{
if(deviceCounts == null)
{
deviceCounts = new List<ServerCount>();
}
var startOfTthisMonth = new DateTime(DateTime.Today.Year,
DateTime.Today.Month, 1);
var FromDate = startOfTthisMonth.AddMonths(-1);
var ToDate = startOfTthisMonth.AddDays(-1);
var billMonth = startOfTthisMonth.AddMonths(-1).ToString("MMM") + "-" + startOfTthisMonth.AddMonths(-1).ToString("yyyy");
ServerCount model = new ServerCount();
foreach (ServerCount sc in deviceCounts)
{
model.BillingMonth = billMonth;
model.ServiceName = sc.ServiceName;
model.BaslineVol = sc.BaslineVol;
model.ResourceUnit = sc.ResourceUnit;
model.DeviceCount = sc.DeviceCount;
model.DeployedServer = sc.DeployedServer;
model.RetiredServer = sc.RetiredServer;
_context.ServerCount.Add(model);
}
int insertRecords = _context.SaveChanges();
return Json(insertRecords);
}
==================
Jquery
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "#btnSave", function () {
var deviceCounts = new Array();
$("#tblServerCount TBODY TR").each(function () {
var row = $(this);
var deviceCount = {};
deviceCount.ServiceName = row.find("TD").eq(0).html();
deviceCount.BaslineVol = row.find("TD").eq(1).html();
deviceCount.ResourceUnit = row.find("TD").eq(2).html();
deviceCount.DeviceCount = row.find("TD").eq(3).html();
deviceCount.DeployedServer = row.find("TD").eq(4).html();
deviceCount.RetiredServer = row.find("TD").eq(5).html();
deviceCounts.push(deviceCount);
});
var model = $("#MyForm").serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Proccess", "DeviceCountServers", new { Area = "Admin" })?' +model,
data: JSON.stringify(deviceCounts),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
location.reload();
});
});
});
</script>
I looking that data from table is saved to sql on click of button

Related

How can I pass JSON formatted data from View to controller action in ASP.NET Core MVC

I am new in.net core MVC. I want to send data from view to controller in JSON format.
I am creating dynamic table for saving data of data. post I want to send this newly added data controller.
Kindly see the logic and update me if anything I doing wrong or how can I achieve my aim.
I want to retrieve the values in SubmitExpense() method
Here is the javascript:
$(function () {
$('#btnSave').on('click', function () {
//alert('1111');
var ExpenseCliamViewModel = {};
var ExpenseClaimLineItems = new Array();
$("#myTable:eq(0) TR").each(function () {
var row = $(this);
var ExpenseClaimLineItem = {};
//ExpenseCliamViewModel.ExpenseClaimLineItem.
ExpenseClaimLineItem.LineItemTitle = row.find("TD").eq(1).html();
ExpenseClaimLineItem.LineItemDescription = row.find("TD").eq(2).html();
ExpenseClaimLineItem.ExpenseTypeName = row.find("TD").eq(3).html();
ExpenseClaimLineItem.LineItemAmount = row.find("TD").eq(4).html();
ExpenseClaimLineItem.LineItemClaimDate = row.find("TD").eq(5).html();
// alert(ExpenseClaimLineItem);
ExpenseClaimLineItems.push(ExpenseClaimLineItem);
});
ExpenseCliamViewModel.ExpenseClaimLineItem = ExpenseClaimLineItems;
ExpenseCliamViewModel.Title = $("#Title").val();
ExpenseCliamViewModel.Description = $("#Description").val();
ExpenseCliamViewModel.TotalAmount = $('#lblGrandTotal').html();
// ExpenseCliamViewModel.Title = $("#Title").val();
console.log(JSON.stringify(ExpenseCliamViewModel));
if (ExpenseCliamViewModel != null) {
$.ajax({
type: "POST",
url: "/Expense/SubmitExpense",
data: JSON.stringify(ExpenseCliamViewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response != null) {
alert('Sucess');
} else {
alert("Something went wrong");
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
else
alert('failed');
});
});
Here is the controller C# method:
[HttpPost]
public JsonResult SubmitExpense(ExpenseCliamViewModel expenseCliamViewModelData)
{
int insertedRecords = 1;
return Json(insertedRecords);
}
In your ajax, try :
$.ajax({
type:'POST',
url:"/Expense/SubmitExpense",
data:ExpenseCliamViewModel,
success:function(data){alert("success")},
error:function(){alert("error")}
});
Update:
Change your code $("#myTable:eq(0) TR") like below :
$("#myTable").find("tr:gt(0)").each(function () {
...
});
Result:

Sensenet Content Picker Customization

I created two custom content types, ProjectContract and PaymentRequest. Under PaymentRequest, I have a reference field Contract which I would like to use to reference ProjectContract. When I am creating/changing PaymentRequest, I need the following:
how can I initialize Content Picker to display ContractNumber field of available ProjectContracts?
how can I display selected ProjectContract's ContractNumber under ReferenceField Grid control?
The SN js code and the mvc contains/returns fix field values. I did not find any setting where I can add custom fields to show.
First of all, what is the version of that SN package, because the oData.svc request will not work on older versions. It is available from 6.2.
About the oData, here is a link: http://wiki.sensenet.com/OData_REST_API
There is another way to solve it, but with this, you need to modify the existion SN codes.
You need to copy (" /Root/Global/scripts/sn/SN.Picker.js ") file into your skin folder with the same structure. (" /Root/Skins/[yourskinfolder]/scripts/sn/SN.ReferenceGrid.js ")
You need to copy (" /Root/Global/scripts/sn/SN.ReferenceGrid.js ") file into your skin folder as well.
Do not modify the original SN file, because it will be overwrite after an SN update.
Next step: copy the following code to line 1068, before the ("$grid.jqGrid({") line, into the InitGrid function.
...
var neededTypeName = "ProjectContract";
var neededFieldName = "ContractNumber";
var findField = false;
o2 = (function () {
var result = [];
var itemArray = [];
$.each(o2, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
colNames.splice(6, 0, "ContentField");
colModel.splice(6, 0, { index: "ContentField", name: "ContentField", width: 100 });
return result;
}
return o2;
})();
...
$grid.jqGrid({
...
The "neededTypeName" may contains your content type value, and the "neededFieldName" may contains the field name you want to render.
The other will build up the grid.
This will modify the Content picker table.
You need to add this code into the GetResultDataFromRow function, at line 660 before the return of the function.
...
if (rowdata.ContentField != undefined) {
result.ContentField = rowdata.ContentField;
}
...
This will add the selected item properties from the Content picker to the reference field table.
Then you need to open the SN.ReferenceGrid.js and add the following code into the init function before the "var $grid = $("#" + displayAreaId);"
var neededTypeName = "CustomItem2";
var neededFieldName = "Custom2Num";
var findField = false;
var alreadyAdded = false;
var btnAttr = $("#"+addButtonId).attr("onClick");
if (btnAttr.indexOf(neededTypeName) > -1) {
alreadyAdded = true;
colNames[4].width = 150;
colModel[4].width = 150;
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 60 });
}
initialSelection = (function () {
var result = [];
var itemArray = [];
$.each(initialSelection, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
if (!alreadyAdded) {
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 100 });
}
return result;
}
return initialSelection;
})();
I hope this will help but the SN version should be helpful.

MVC ResultStream only working with link

I'm creating a barcode using ASP.Net MVC
The problem is it's working with links. But it needs to work with form values.
This is my controller :
[HttpPost]
public ActionResult Barcode(BarcodeModel B)
{
string BarcodeTitle = B.BarkodTitle;
string BarcodeNumber = B.BarcodeNumber;
Codec objbar = new Codec();
Byte[] BarcodeImage = objbar.getBarcodeImage(BarcodeNumber, BarcodeTitle);
Stream Memory = new MemoryStream(BarcodeImage);
Memory.Position = 0;
var Result = new FileStreamResult(Memory, "image/png");
Result.FileDownloadName = String.Format("{0}.png", BarcodeTitle);
return Result ;
}
This is my JavaScript code :
<script type="text/javascript">
function BarkodKaydet()
{
var BarkodModel = new Object();
BarkodModel.DeweyCode = document.getElementById('DeweyCode').value;
BarkodModel.CutterNumber = document.getElementById('CutterNumber').value;
BarkodModel.Year = document.getElementById('Year').value;
BarkodModel.Bind = document.getElementById('Bind').value;
BarkodModel.Copy = document.getElementById('Copy').value;
BarkodModel.BarcodeTitle = document.getElementById('BarcodeTitle').value;
BarkodModel.BarcodeNumber = document.getElementById('BarcodeNumber').value;
$.ajax({
type: "post",
url: "#Url.Action("Barcode")",
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(BarkodModel),
success: function (data) { console.log(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
But it's not working.
It' just working with link how I'm changing controller to ;
public ActionResult Barcode(string barcodeNumber, string barcodeText)
{
Codec objbar = new Codec();
Byte[] BarkodImage = objbar.getBarcodeImage(barcodeNumber, barcodeTitle);
Stream Memory = new MemoryStream(BarcodeImage);
Memory.Position = 0;
var Result = new FileStreamResult(Memory, "image/png");
Result.FileDownloadName = String.Format("{0}.png", BarcodeTitle);
return Result ;
}
this and change view to ;
<img src="/Home/BarcodeImage?barcodeText=Can&barcodeNo=12345" />
to this.
When the page opening, the linked image sending values to controller and showing barcode to me.
But I need;
When the form values submitting to model, ActionResult needs to create barcode from model, refresh the same page and It will show only barcodeImage to me.
How can I configure it ?
Best regards.

SAPUI5 file upload

I am creating an SAPUI5 app that needs to upload attachments. I still am very new use SAPUi5. I want to save the uploaded file to the DB. Could I use the Document service? If so please provide me with docs or tutorials to do so.
I have done that in one off my SAPUI5 apps, for the uploading function check out my gist.
Or check this for reference
onUpload: function(e) {
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
};
reader.readAsBinaryString(file);
}
Irrespective of whether you use DB or Document Service, with respect to SAPUI5,
you can use sap.ui.unified.FileUploader. Read more here
Sample XML code would be:
<sap.ui.unified:FileUploader
id="fileUploader"
width="100%"
uploadUrl=""
placeholder="Add attachment"
uploadOnChange="false"
uploadComplete="handleUploadComplete"
change="handleValueChange"
typeMissmatch="handleTypeMissmatch"
style="Emphasized"
useMultipart="false" >
</sap.ui.unified:FileUploader>
While uploading make sure, you add slug and x-csrf-token to the headerparameters.
Example:
var oFileUploader = _this.byId("fileUploader");
oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
name: "slug",
value: oFileUploader.getValue()
}));
oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
name: "x-csrf-token",
value: _this.oDataModel.getSecurityToken()
}));
oFileUploader.upload();
And if you are using ABAP Netweaver gateway stack, you need to implement CREATE_STREAM method in DPC_EXT classes. Also need to make sure that pareticular EventType with "media" supported in Gateway model.
uploadFile:function{
var that = this;
var count = 0;
var o = "<URI>";
var h = new sap.ui.model.odata.ODataModel(o, true);
var d = "";
h.setSizeLimit(5000);
h.forceNoCache(true);
var b = ({
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
"X-CSRF-Token": "Fetch",
});
OData.request({
requestUri: o,
method: "GET",
headers: b
}, function (e, j) {
d = j.headers["x-csrf-token"];
that.csrfToken = d;
that.getModel("oAppData").setProperty("/busyIndicators/uploadFile", true);
for (var l = 0; l < that.fileDataAD.length; l++) {
var i = "<URI>";
var h = new sap.ui.model.odata.ODataModel(i, true);
h.setSizeLimit(5000);
h.forceNoCache(true);
var b = ({
"X-CSRF-Token": that.csrfToken,
"Slug": that.fileDataAD[l].fileName + "|" + that.fileDataAD[l].fileType + "|" + "B" + "|" + reqId + "|" + 1
});
OData.request({
requestUri: i,
method: "POST",
headers: b,
data: that.fileDataAD[l].file
}, function (oData, oRes) {
count = count + 1;
if (count === that.fileDataAD.length) {
that._uploadCompleteAddDependent();
}
}.bind(this), function (oError) { }
}
});
}
where fileDataAD is buffer array

Write grid to text file in html format

I have a data grid. I want to submit this data to the server and store it in a text file.
Here's the code I have so far:
var tbl = $('table#grid tbody tr').map(function (idx, el) {
var td = $(el).find('td');
var obj = { id: idx + 1 };
for (var i = 0; i < tblhdr.length; i++) {
obj[tblhdr[i]] = td.eq(i).text();
}
return obj;
}).get();
tbl = JSON.stringify(tbl);
var request = $.ajax({
url: "../reports/S?tbl=" + tbl,//action method url which defined in controller
type: 'POST',
cache: false,
data: JSON.stringify(tbl),
dataType: 'text',
contentType: 'application/text'
});
[HttpPost,ValidateInput(false)]
public ActionResult reports(string tbl)
{
string table = tbl;
StreamWriter file2 = new StreamWriter(#"D:\Demo.txt", true);
file2.WriteLine(tbl);
file2.Flush();
file2.Close();
}
I need the data in HTML form.