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 });
}
}
Related
I have a list of 10 questions, used in rating a user, something like this:
The list is gotten dynamically, based on the users Occupation. This is how I am getting the list:
#for (int i = 0; i < Model.AppraisalQuestions.ToList().Count; i++)
{
#Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionId)
#Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionDescription)
<p>
#Html.DisplayFor(m => m.AppraisalQuestions[i].QuestionDescription)
#Html.ValidationMessageFor(m => m.AppraisalQuestions[i].SelectedAnswer, "", new { #class = "text-danger" })
</p>
<div class="row lead evaluation">
<div id="colorstar" class="starrr ratable"></div>
<span id="count">0</span> star(s) - <span id="meaning"> </span>
#foreach (var answer in Model.AppraisalQuestions[i].PossibleAnswers)
{
//var inputId = Model.AppraisalQuestions[i].QuestionId + "-" + answer.ID;
#Html.HiddenFor(m => m.AppraisalQuestions[i].SelectedAnswer, new { id = "SelectedAns", required = "required" })
}
</div>
}
This is the model:
public class AppraisalInputModel
{
public int AppraisalId { get; set; }
public AppraisalInputModel()
{
AppraisalQuestions = new List<AppraisalQuestionInputModel>();
}
public string FullName { get; set; }
public string JobTitle { get; set; }
public int StaffId { get; set; }
public int ScorerId { get; set; }
public int BranchId { get; set; }
public string AppraisalTitle { get; set; }
public IList<AppraisalQuestionInputModel> AppraisalQuestions { get; set; }
}
and this is the AppraisalQuestionInputModel
public class AppraisalQuestionInputModel
{
public int QuestionId { get; set; }
public string QuestionDescription { get; set; }
public bool IsGeneral { get; set; }
[Required]
[Display(Name = "Score")]
public int? SelectedAnswer { get; set; }
public IEnumerable<AnswerVM> PossibleAnswers => new List<AnswerVM>()
{
new AnswerVM {ID = 1, Text = "1 - Poor"},
new AnswerVM {ID = 2, Text = "2 - Below Expectation"},
new AnswerVM {ID = 3, Text = "3 - Meets Expectation"},
new AnswerVM {ID = 4, Text = "4 - Good"},
new AnswerVM {ID = 5, Text = "5 - Excellent"},
};
}
This is the script section code:
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
// Starrr plugin (https://github.com/dobtco/starrr)
var __slice = [].slice;
(function($, window) {
var Starrr;
Starrr = (function() {
Starrr.prototype.defaults = {
rating: void 0,
numStars: 5,
change: function(e, value) {}
};
function Starrr($el, options) {
var i,
_,
_ref,
_this = this;
this.options = $.extend({}, this.defaults, options);
this.$el = $el;
_ref = this.defaults;
for (i in _ref) {
_ = _ref[i];
if (this.$el.data(i) != null) {
this.options[i] = this.$el.data(i);
}
}
this.createStars();
this.syncRating();
this.$el.on('mouseover.starrr', 'span', function(e) {
return _this.syncRating(_this.$el.find('span').index(e.currentTarget) + 1);
});
this.$el.on('mouseout.starrr', function() {
return _this.syncRating();
});
this.$el.on('click.starrr', 'span', function(e) {
return _this.setRating(_this.$el.find('span').index(e.currentTarget) + 1);
});
this.$el.on('starrr:change', this.options.change);
}
Starrr.prototype.createStars = function() {
var _i, _ref, _results;
_results = [];
for (_i = 1, _ref = this.options.numStars; 1 <= _ref ? _i <= _ref : _i >= _ref; 1 <= _ref ? _i++ : _i--) {
_results.push(this.$el.append("<span class='glyphicon .glyphicon-star-empty'></span>"));
}
return _results;
};
Starrr.prototype.setRating = function(rating) {
if (this.options.rating === rating) {
rating = void 0;
}
this.options.rating = rating;
this.syncRating();
return this.$el.trigger('starrr:change', rating);
};
Starrr.prototype.syncRating = function(rating) {
var i, _i, _j, _ref;
rating || (rating = this.options.rating);
if (rating) {
for (i = _i = 0, _ref = rating - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
this.$el.find('span').eq(i).removeClass('glyphicon-star-empty').addClass('glyphicon-star');
}
}
if (rating && rating < 5) {
for (i = _j = rating; rating <= 4 ? _j <= 4 : _j >= 4; i = rating <= 4 ? ++_j : --_j) {
this.$el.find('span').eq(i).removeClass('glyphicon-star').addClass('glyphicon-star-empty');
}
}
if (!rating) {
return this.$el.find('span').removeClass('glyphicon-star').addClass('glyphicon-star-empty');
}
};
return Starrr;
})();
return $.fn.extend({
starrr: function() {
var args, option;
option = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return this.each(function() {
var data;
data = $(this).data('star-rating');
if (!data) {
$(this).data('star-rating', (data = new Starrr($(this), option)));
}
if (typeof option === 'string') {
return data[option].apply(data, args);
}
});
}
});
})(window.jQuery, window);
$(function() {
return $(".starrr").starrr();
});
$(document).ready(function () {
var starCount;
var correspondence = ["", "Poor", "Below Expectation", "Above Expectation", "Good", "Excelent"];
$('.ratable').on('starrr:change', function(e, value) {
$(this).closest('.evaluation').children('#count').html(value);
$(this).closest('.evaluation').children('#SelectedAns').val(value);
starCount = $(this).closest('.evaluation').children('#SelectedAns').val(value);
if (starCount === null) {
swal("", "Please Enter First Name", "error");
}
$(this).closest('.evaluation').children('#meaning').html(correspondence[value]);
var currentval = $(this).closest('.evaluation').children('#count').html();
var target = $(this).closest('.evaluation').children('.indicators');
target.css("color", "black");
target.children('.rateval').val(currentval);
target.children('#textwr').html(' ');
});
$('#hearts-existing').on('starrr:change', function(e, value) {
$('#count-existing').html(value);
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
});
</script>
}
And all questions must be answered. How Do I validate to make sure that all questions are answered?
I have tried form.Validate() but it is not working.
Your view is generating 5 hidden inputs for the same SelectedAnswer. You need only one (only the value of the first one will be bound by the DefaultModelBinder), and you need to set its value in the starrr:change event.
However, hidden inputs are not validated by default so you also need to configure the $.validator to give you client side validation.
First, modify your view to delete the foreach loop and replace it with a single hidden input. Note also the id attributes have been replaced with class names (duplicate id attributes is invalid html)
#for (int i = 0; i < Model.AppraisalQuestions.ToList().Count; i++)
{
#Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionId)
#Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionDescription)
<p>
#Html.DisplayFor(m => m.AppraisalQuestions[i].QuestionDescription)
#Html.ValidationMessageFor(m => m.AppraisalQuestions[i].SelectedAnswer, "", new { #class = "text-danger" })
</p>
<div class="row lead evaluation">
<div class="starrr ratable"></div> // remove invalid id attribute
<span class="count">0</span> star(s) - <span class="meaning"> </span>
#Html.HiddenFor(m => m.AppraisalQuestions[i].SelectedAnswer, new { #class = "rating" })
</div>
}
Then to set the value of the input so it is posted back when you submit the form
$('.ratable').on('starrr:change', function(e, value) {
var container = $(this).closest('.evaluation'); // cache it
container.children('.count').html(value); // modify
container.children('.rating').val(value); // set value of input
container.children('.meaning').html(correspondence[value]); // modify
....
})
Note the code relating to starCount does not seem necessary, and its not clear what some of the other code in that method is doing or why you have it (for example currentval is just the same value as value)
Finally, to get client side validation, add the following script (but not inside document.ready())
$.validator.setDefaults({
ignore: ":hidden:not('.rating')"
});
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 am currently writing an API with Express.js and have seen many examples about how to create schemas/models for mongodb, but was wondering if there is any similar solution for MSSQL. For example, I have the following method in a C# controller:
public void SubmitExpenses(List<Expense> expenses)
{
using (cnxn)
{
cnxn.Open();
for (int i = 0; i < expenses.Count; i++)
{
int employeeId = expenses.ElementAt(i).employeeId;
string expenseDate = expenses.ElementAt(i).expenseDate;
int taskId = expenses.ElementAt(i).taskId;
int expenseTypeId = expenses.ElementAt(i).expenseTypeId;
int billingCategory = expenses.ElementAt(i).billingCategory;
string notes = expenses.ElementAt(i).notes;
float amount = expenses.ElementAt(i).amount;
string lastUpdatedDate = expenses.ElementAt(i).LastUpdatedDate;
int lastUpdatedBy = expenses.ElementAt(i).LastUpdatedBy;
string dateSubmitted = expenses.ElementAt(i).dateSubmitted;
//public void SubmitExpenses(int employeeId, string expenseDate, int taskId, int expenseTypeId, int billingCategory,
// string notes, float amount, string lastUpdatedDate, int lastUpdatedBy, string dateSubmitted)
//{
using (SqlCommand sqlQuery = new SqlCommand("INSERT INTO Expenses " +
"(Employee_ID, Task_ID, Expense_Date, Expense_Type_ID, Billing_Category_ID, " +
"Amount, Notes, Last_Updated_By, Last_Update_Datetime, Date_Submitted, Location) " +
"Values (#employeeId, #taskId, #expenseDate, #expenseTypeId, #billingCategory, #amount, #notes, " +
"#lastUpdatedBy, #lastUpdatedDate, #dateSubmitted, #locationId)", cnxn))
{
sqlQuery.Parameters.Add(new SqlParameter("#employeeId", SqlDbType.Int) { Value = employeeId });
sqlQuery.Parameters.Add(new SqlParameter("#expenseDate", SqlDbType.DateTime) { Value = expenseDate });
sqlQuery.Parameters.Add(new SqlParameter("#taskId", SqlDbType.Int) { Value = taskId });
sqlQuery.Parameters.Add(new SqlParameter("#expenseTypeId", SqlDbType.Int) { Value = expenseTypeId });
sqlQuery.Parameters.Add(new SqlParameter("#billingCategory", SqlDbType.Int) { Value = billingCategory });
sqlQuery.Parameters.Add(new SqlParameter("#notes", SqlDbType.Text) { Value = notes });
sqlQuery.Parameters.Add(new SqlParameter("#amount", SqlDbType.Money) { Value = amount });
sqlQuery.Parameters.Add(new SqlParameter("#lastUpdatedDate", SqlDbType.DateTime) { Value = lastUpdatedDate });
sqlQuery.Parameters.Add(new SqlParameter("#lastUpdatedBy", SqlDbType.Int) { Value = lastUpdatedBy });
sqlQuery.Parameters.Add(new SqlParameter("#dateSubmitted", SqlDbType.DateTime) { Value = dateSubmitted });
sqlQuery.Parameters.Add(new SqlParameter("#locationId", SqlDbType.VarChar) { Value = "" });
sqlQuery.ExecuteNonQuery();
}
}
}
}
And the Expense.cs model:
public class Expense
{
public int employeeId { get; set; }
public string expenseDate { get; set; }
public int taskId { get; set; }
public int expenseTypeId { get; set; }
public int billingCategory { get; set; }
public string notes { get; set; }
public float amount { get; set; }
public string LastUpdatedDate { get; set; }
public int LastUpdatedBy { get; set; }
public string dateSubmitted { get; set; }
public string location { get; set; }
}
How would I go about in similar fashion in Express.js so I could take a list of JavaScript objects, break them into elements which could then be parameterized and submitted?
Would it be something like...
app.post('/route/to/api', function (req, res) {
var sql = require('mssql');
sql.connect("mssql://user:password#localhost/Northwind").then(function () {
console.log('connected');
for (var i = 0; i < req.length; i++) {
new sql.Request()
.input('input_param', sql.VARCHAR, req[i]['PropertyName'])
.query('INSERT INTO Table VALUES (#input_param)')
.then(function (recordset) {
console.log(recordset);
})
.catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
console.log(err);
});
});
Any advice would be much appreciated!
Have a look at sequelize. It should give you the functionality you require.
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
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();
}