This is my javascript code:
var bankOptions = {};
var playerOptions = [];
bankOptions["BankTotalAmount"] = $("#totalBankAmountID").val();
bankOptions["SinglePlayerAmount"] = $("#singlePlayerAmountID").val();
while (_playerNumber != 0) {
if (_playerNumber == 1) {
var player1Option = {};
player1Option["Name"] = $("#p" + _playerNumber + "Name").val();
player1Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player1Option);
}
if (_playerNumber == 2) {
var player2Option = {};
player2Option["Name"] = $("#p" + _playerNumber + "Name").val();
player2Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player2Option);
}
if (_playerNumber == 3) {
var player3Option = {};
player3Option["Name"] = $("#p" + _playerNumber + "Name").val();
player3Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player3Option);
}
if (_playerNumber == 4) {
var player4Option = {};
player4Option["Name"] = $("#p" + _playerNumber + "Name").val();
player4Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player4Option);
}
_playerNumber--;
}
alert(playerOptions);
$.ajax({
url: "/StartOption/setOptions/",
contentType: 'application/json',
data: JSON.stringify({ bankOptions: bankOptions, playerOptions: playerOptions }),
type: "POST",
timeout: 10000,
success: function (result) {
}
});
and i have this Controller class
public class StartOptionController : Controller
{
private MonopolyDB db = new MonopolyDB();
//
// GET: /StartOption/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
//return RedirectToAction("Index");
return View();
}
}
public class BankOptions
{
public int BankTotalAmount { get; set; }
public int SinglePlayerAmount { get; set; }
}
public class Playeroptions
{
public string Name { get; set; }
public string Color { get; set; }
}
My question is how i can get those object array that i push into playerOptions object array in my setOptions action?
as like i want to save each player info in my DB from playerOptions object array where i push each player info in my javascript code.
Well first to make it easy I would like to recommend that changes the sign of your action
from
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
To
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
That's it's going to make it easy the handle of each element of the array, and there's not problem for the framework to serialize this object.
Now to answer your question you could iterate the array like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
for ( int i = 0 ; i< playerOptions.Length, i++)
{
playerOptions[i]; //<-- this give's the specific element
}
//return RedirectToAction("Index");
return View();
}
Nevertheless if you follow my recommendation and changes the sign of your action you could iterate your code like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
foreach( var item in playerOptions){
item //<--- in this variable you have the element PlayerOption
}
//return RedirectToAction("Index");
return View();
}
Related
I have holding object as follows:
public class Transfer implements Serializable {
private Integer transferId;
private Integer transferTypeId;
private String storeId;
private String userId;
private Integer titleId;
private Integer statusId;
private String inWorkerId;
private String outWorkerId;
private Date createDt;
private Date updateDt;
// getters & setts
}
And I have var reqRow that need to be sent to the controller
function onClickSave(){
var rows = $('#transferEditGrid').jqGrid('getRowData');
var reqRow = [];
for (i = 0; i < rows.length; i++)
{
var rowObj = {};
rowObj.storeId = rows[i].storeId;
rowObj.inWorkerId = rows[i].inWorkerId;
rowObj.outWorkerId = rows[i].outWorkerId;
rowObj.transferTypeId = rows[i].transferTypeId;
rowObj.statusId = rows[i].statusId;
rowObj.storeId = rows[i].storeId;
reqRow.push(rowObj);
}
//send reqRow to the Controller
$.ajax({
type:'POST',
url:'${contextPath}/resource-transfer/update.do',
dataType:"json",
data : {rows : reqRow},
//data:JSON.stringify(reqRow),
success:function(response){
alert("success");
}
});
}
The controller is following :
#RequestMapping(value = "/update", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
#ResponseBody
public String transferUpdate(#RequestBody List<Transfer> rows) throws JSONException, InterruptedException {
System.out.println("in transfer update section");
return null;
}
Why I could not pass the array object to the controller?
Did I misunderstand the usage of the Ajax call?
Thank you
First, wrap List to another java object
public class TransferDTO {
private List<Transfer> rows;
// getter & setter
}
Use this inplace of List<Transfer> in your endpoint.
public String transferUpdate(#RequestBody TransferDTO data)
Specify contentType in your AJAX post
contentType: 'application/json'
Manually stringify the data
data : JSON.stringify({rows: reqRow})
Java code
#Controller
public class ContractController {
#RequestMapping(value="all/contract/change/detail", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
#ResponseStatus(HttpStatus.OK)
public List<ContractAndBidReceiveChangeDetailModel> getAllContractAndBidReceiveChangeDetail(#RequestBody List<ContractReceivedChangedActivityCodesModel> allChangedActivityCodesModel) {
List<ContractAndBidReceiveChangeDetailModel> allContractAndBidChangeDetails = null;
if (CollectionUtils.isNotEmpty(allChangedActivityCodesModel)) {
allContractAndBidChangeDetails = allChangedActivityCodesModel
.stream()
.map(this::getContractAndBidReceiveChangeDetail)
.collect(Collectors.toList());
}
return allContractAndBidChangeDetails;
}
} // end of controller class
#JsonAutoDetect(
creatorVisibility = JsonAutoDetect.Visibility.NONE,
fieldVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE
)
public class ContractReceivedChangedActivityCodesModel {
private String rowId;
private Long bidId;
private Long planId;
private Long optionCodeId;
private Long activityCodeId;
private Long activityPackageId;
private String activityCodeNoAndName;
private String planName;
// constructors
#JsonProperty
public String getRowId() {
return rowId;
}
public void setRowId(String rowId) {
this.rowId = rowId;
}
//others getters and setters
}
JQuery code. Make sure you make the same json rquest that spring is expecting. Spring will automatically map this json to your java List
function getDetailRow(url, requestData, $caret, action) {
$spinner.show();
$.ajax({
url: url,
data : requestData,
dataType: "json",
type: "POST",
contentType: "application/json",
success: function(response) {
if (!$.isEmptyObject(response)) {
switch(action){
case "expandLink":
insertDetailRow($caret, response);
break;
case "expandAllLinks":
$.each(response, function(index, changeDetailResponse) {
var caretId = changeDetailResponse.rowId;
let $caret = $('#' + caretId);
insertDetailRow($caret, changeDetailResponse);
});
break;
}
}
$spinner.hide();
}, error: function(xhr, status, error){
$spinner.hide();
if (xhr.status == 500) {
var errorResponse = xhr.responseText;
if (errorResponse) {
alert(errorResponse);
}
}
}
});
}
function getRequestJson(requestObject) {
let requestJson = null;
if (requestObject != null) {
requestJson = JSON.stringify(requestObject);
}
return requestJson;
}
function getRequestObject($caret) {
let requestObject = null;
if ($caret.length > 0) {
let rowId = $caret.attr("id");
let bidId = $caret.attr("bidId");
let planId = $caret.attr("planId");
let optionCodeId = $caret.attr("optionCodeId");
let activityCodeId = $caret.attr("activityCodeId");
let activityPackageId = $caret.attr("activityPackageId");
requestObject = new Object();
requestObject.rowId = rowId;
requestObject.bidId = bidId;
requestObject.planId = planId;
requestObject.optionCodeId = optionCodeId;
requestObject.activityCodeId = activityCodeId;
requestObject.activityPackageId = activityPackageId;
}
return requestObject;
}
let caretsWithoutDetailRow = new Array();
let requestObjects = null;
// process caretsWithoutDetailRow Array with some logic so it contains some elements
if (caretsWithoutDetailRow.length > 0) {
requestObjects = new Array();
$.each(caretsWithoutDetailRow, function(index, $caret) {
let requestObject = getRequestObject($caret);
requestObjects.push(requestObject);
});
}
if (requestObjects != null && requestObjects.length > 0) {
let requestObjectsJson = getRequestJson(requestObjects);
let url = '<c:url value = "/all/contract/change/detail"/>';
getDetailRow(url, requestObjectsJson, null, 'expandAllLinks');
}
i have a problem in passing model objects to a javascript function in .cshtml(asp.net Core project).
I have done a lot of search,but can't find a solution to solve this problem.
I build a web application use ChartJs line sample.
web app
js files
There is a js function in .cshtml file,
<script>
document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
config.data.datasets.forEach(function(dataset) {
dataset.data.push(randomScalingFactor());
});
window.myLine.update();
}
});
</script>
I'm new to asp.net core and js.
If there is a way to add data from model to js function?
Thanks!
I have solved this problem!
Solution:
Model:
public class SalesViewModel
{
public string salesdate { get; set; }
public int salesprice { get; set; }
}
Data:
public class SalesContext
{
public string ConnectionString { get; set; }
public SalesContext(string connectionString)
{
this.ConnectionString = connectionString;
}
public SalesContext()
{
}
public List<SalesViewModel> GetAllData()
{
List<SalesViewModel> list = new List<SalesViewModel>();
list.Add(new SalesViewModel() { salesdate = "1", salesprice = 3 });
list.Add(new SalesViewModel() { salesdate = "2", salesprice = 6 });
list.Add(new SalesViewModel() { salesdate = "3", salesprice = 7 });
list.Add(new SalesViewModel() { salesdate = "4", salesprice = 2 });
list.Add(new SalesViewModel() { salesdate = "5", salesprice = 1 });
return list;
}
}
Controller:
using Newtonsoft.Json;
public IActionResult Chart()
{
SalesContext sc = new SalesContext();
string json = JsonConvert.SerializeObject(sc.GetAllData());
//ViewData["chart"] = json;
ViewBag.Sales = json;
return View(sc.GetAllData());
}
View:
document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
var salesdata = #Html.Raw(ViewBag.Sales);
config.data.datasets.forEach(function(dataset) {
for (var i = 0; i < salesdata.length; i++) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
dataset.data.push(salesdata[i].salesprice);
}
});
window.myLine.update();
}
});
use var salesdata = #Html.Raw(ViewBag.Sales) to get data from controller!
use salesdata[i].salesprice to push data to the dataset!
Thanks!
I try to put the plugin blueimp to my Asp.Net MVC application.
My upload target is about 1GB.
How to handle chunk file upload fle in server side?
I suppose you mean FileUpload jquery module from blueimp. This is how I handle it in my project. I upload large images that don't go over 30MB. So this example is merely about the code, not the fact that you need to handle 1GB files.
This is part of the javascript code. There's nothing special. I just follow the FileUpload documentation and example. I just send couple more properties (inlcuding AntiforgeryToken) - that are not required for the correct behavior.
$("#file-upload").fileupload({
url: 'upload-file',
dataType: 'json',
autoUpload: false,
maxChunkSize: 5000000,
progressInterval: 1000,
bitrateInterval: 1000
}).on('fileuploadadd', function (e, data) {
fileData = data; // save data to be able to submit them later
if (window.File && window.Blob) {
// update form data
data.formData = {
uploadFolder: '/upload-folder/some-guid',
__RequestVerificationToken: $("#upload-form").find('input[name=__RequestVerificationToken]').val()
};
} else {
// chunk upload not supported
}
});
$("#file-submit").on('click', function (e) {
e.preventDefault();
fileData.submit();
});
On the server side I have a model class:
public class UploadViewRequest
{
public Guid UploadFolder { get; set; }
public bool IsChunk { get; set; }
public int ChunkNumber { get; set; }
public bool IsFirst { get; set; }
public bool IsLast { get; set; }
public HttpPostedFileBase OriginalFile { get; set; }
public bool JsonAccepted { get; set; }
}
And I wrote a custom model binder for this class, so that I can see if it's whole file or just a chunk and if yes, that what part of the file I'm going to process:
public class UploadViewRequestBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
UploadViewRequest model = base.BindModel(controllerContext, bindingContext) as UploadViewRequest;
string rangeHeader = controllerContext.HttpContext.Request.Headers["Content-Range"];
if (string.IsNullOrEmpty(rangeHeader))
model.IsChunk = false;
else
{
model.IsChunk = true;
Match match = Regex.Match(rangeHeader, "^bytes ([\\d]+)-([\\d]+)\\/([\\d]+)$", RegexOptions.IgnoreCase);
int bytesFrom = int.Parse(match.Groups[1].Value);
int bytesTo = int.Parse(match.Groups[2].Value);
int bytesFull = int.Parse(match.Groups[3].Value);
if (bytesTo == bytesFull)
model.IsLast = true;
else
model.IsLast = false;
if (bytesFrom == 0)
{
model.ChunkNumber = 1;
model.IsFirst = true;
}
else
{
int bytesSize = bytesTo - bytesFrom + 1;
model.ChunkNumber = (bytesFrom / bytesSize) + 1;
model.IsFirst = false;
}
}
if (controllerContext.HttpContext.Request["HTTP_ACCEPT"] != null && controllerContext.HttpContext.Request["HTTP_ACCEPT"].Contains("application/json"))
model.JsonAccepted = true;
else
model.JsonAccepted = false;
return model;
}
}
and this is the controller action method:
public ActionResult Upload(UploadViewRequest request)
{
var path = ''; // create path
FileStatus status = null;
try
{
if (request.IsChunk)
{
if (request.IsFirst )
{
// do some stuff that has to be done before the file starts uploading
}
var inputStream = request.OriginalFile.InputStream;
using (var fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
var buffer = new byte[1024];
var l = inputStream.Read(buffer, 0, 1024);
while (l > 0)
{
fs.Write(buffer, 0, l);
l = inputStream.Read(buffer, 0, 1024);
}
fs.Flush();
fs.Close();
}
status = new FileStatus(new FileInfo(path));
if (request.IsLast)
{
// do some stuff that has to be done after the file is uploaded
}
}
else
{
file.SaveAs(path);
status = new FileStatus(new FileInfo(path));
}
} catch {
status = new FileStatus
{
error = "Something went wrong"
};
}
// this is just a browser json support/compatibility workaround
if (request.JsonAccepted)
return Json(status);
else
return Json(status, "text/plain");
}
The FileStatus class I use as a return value and transform it into json (for the UploadFile jquery module):
public class FileStatus
{
public const string HandlerPath = "/";
public string group { get; set; }
public string name { get; set; }
public string type { get; set; }
public int size { get; set; }
public string progress { get; set; }
public string url { get; set; }
public string thumbnail_url { get; set; }
public string delete_url { get; set; }
public string delete_type { get; set; }
public string error { get; set; }
public FileStatus()
{
}
public FileStatus(FileInfo fileInfo)
{
SetValues(fileInfo.Name, (int)fileInfo.Length, fileInfo.FullName);
}
public FileStatus(string fileName, int fileLength, string fullPath)
{
SetValues(fileName, fileLength, fullPath);
}
private void SetValues(string fileName, int fileLength, string fullPath)
{
name = fileName;
type = "image/png";
size = fileLength;
progress = "1.0";
url = HandlerPath + "/file/upload?f=" + fileName;
delete_url = HandlerPath + "/file/delete?f=" + fileName;
delete_type = "DELETE";
thumbnail_url = "/Content/img/generalFile.png";
}
}
I added checkbox dynamically in the view with PropertiesList select box. When submiting the form it posted the checkbox data but in controller Properties in null that presented in below image.
Browser header:
Debugging mode:
Model:
public class ModelView
{
[HiddenInput]
public int Id { get; set; }
public string Title { get; set; }
public IEnumerable<SelectListItem> PropertiesList { get; set; }
public List<PropertyModels> Properties { get; set; }
}
public class PropertyModels
{
public int PropertyID { get; set; }
public string PropertyIcon { get; set; }
public int PropertyType { get; set; }
public string PropertyName { get; set; }
public bool IsSelected { get; set; }
}
View:
<div class="form-group">
<label>Properties</label>
<select id="PropertiesList" class="form-control" placeholder="Add ...">
#for (var i = 0; i < Model.Properties.Count(); i++)
{
<option value="#Model.Properties[i].PropertyID" data-value="#Model.Properties[i].IsSelected" data-icon="#Model.Properties[i].PropertyIcon">#Model.Properties[i].PropertyName</option>
}
</select>
</div>
<div>
<dl class="dl-horizontal"></dl>
</div>
JQuery:
$("#PropertiesList").on("change", function (e) {
var id = $(this).val();
var icon = $('#PropertiesList option:selected').attr('data-icon');
var name = $('#PropertiesList option:selected').text();
var dt = "<dt><span class='" + icon + "'></span> <span>" + name + "</span></dt>";
var value = ($('#PropertiesList option:selected').attr('data-value') === "True");
var dd = "<dd><input id='Properties_" + id + "__IsSelected' name='Properties[" + id + "].IsSelected' type='checkbox' class='minimal' value='false'> \
<input name='Properties[" + id + "].IsSelected' type='hidden'></dd>";
}
$('.dl-horizontal').append(dt + dd);
});
Conrtoller:
public virtual ActionResult EditView(int Id)
{
List<PropertyModels> PropertyItems = new List<PropertyModels>();
using (var context = new DB())
{
var properties = context.Property
.Where(prpinfo => prpinfo.Status == true)
.Select(prpinfo => new
{
prp_id = prpinfo.PropertyID,
prp_name = prpinfo.PropertyName
prp_icon = prpinfo.PropertyIcon,
});
foreach (var prp in properties)
{
PropertyModels prop = new PropertyModels();
prop.PropertyID = prp.prp_id;
prop.PropertyName = prp.prp_name.FirstOrDefault().prp_name;
prop.PropertyIcon = prp.prp_icon;
prop.IsSelected = false;
PropertyItems.Add(prop);
}
AddPlanModelView EPW = new AddPlanModelView()
{
Properties = PropertyItems
};
return View(EPW);
}
}
[HttpPost]
public virtual ActionResult EditView(ModelView MW)
{
if (TryUpdateModel(Plan, includeProperties: new[] { "PlanId","Title","Properties" }))
{
if (ModelState.IsValid)
{
using (var context = new DB())
{
var selected_property = context.ModelProperty.Where(d => d.ID == MW.Id)
.Select(prpinfo => new
{
prp_id = prpinfo.PropertyID,
prp_val = prpinfo.PropertyValueID
}).ToList();
IList<ModelProperty> modelprps = new List<ModelProperty>();
foreach (var cc in ModelView .Properties)
{
var match = selected_property.Where(c => c.prp_id == cc.PropertyID).Count();
if (match == 0)
{
modelprps.Add(new ModelProperty() { ModelID = Plan.PlanId, PropertyID = cc.PropertyID, Value = cc.IsSelected.ToString() });
}
}
context.ModelProperty.AddRange(modelprps);
}
}
context.SaveChanges();
return Json(new { success = true });
}
}
else
{
return Json(new { success = false });
}
}
else
{
return Json(new { success = false });
}
}
I have a model that i want to send message for special user when add new item of my model.
I add a hub.
public class VisitHub: Hub
{
public void Update(string user, VisitNotification visit)
{
Clients.User(user).update(visit);
}
}
public class VisitNotification
{
public string Referred { get; set; }
public string VisitType { get; set; }
public int ReferredId { get; set; }
public DateTime VisitedDate { get; set; }
}
and in Controller, when i add item.
var visitHub = GlobalHost.ConnectionManager.GetHubContext<VisitHub>();
visitHub.Clients.User(user.UserName).update(new VisitNotification() { Referred = reff.Name + " " + reff.Family, ReferredId = model.ReferredId, VisitType =type.Title, VisitedDate = visit.VisitDate });
}
and in javascript .
function Visit(data, hub) {
var self = this;
self.hub = hub;
data = data || {};
self.Referred = data.Referred || "";
self.ReferredId = data.Referred || 0;
self.VisitType = data.VisitType || "";
self.VisitedDate = getTimeAgo(data.VisitedDate);
}
function viewModel() {
var self = this;
self.newVisit = ko.observable();
self.error = ko.observable();
//SignalR related
self.newVisits = ko.observableArray();
// Reference the proxy for the hub.
self.hub = $.connection.VisitHub;
self.loadNewVisits = function () {
self.visits(self.newVisit().concat(self.visits()));
self.newPosts([]);
}
//functions called by the Hub
self.hub.client.loadVisits = function (data) {
var mappedVisits = $.map(data, function (item) { return new Visit(item, self.hub); });
self.visits(mappedVisits);
}
self.hub.client.update = function (Visit) {
self.newVisit.splice(0, 0, new Visit(Visit, self.hub));
}
self.hub.client.error = function (err) {
self.error(err);
}
return self;
};
var vmVisit = new viewModel();
ko.applyBindings(vmVisit);
$.connection.hub.start().done(function () {
vmVisit.init();
});
and in view.
<span data-bind=" text: newVisits().length" class="badge bg-important"></span>
But don't show any value.
Is the user authenticated? Signalr will only recognize the user if the connections are mapped to the user. Check this link on how to map signalr connections to users: http://www.google.co.uk/url?q=http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections&sa=U&ei=Tjj-VJuPMsPBOZGGgYgH&ved=0CAsQFjAA&usg=AFQjCNFXoGJOm3mzenAJbz46TUq-Lx2bvA