I am building a scheduling system using fullcalendar for MVC, my get event retrieves from a view for a specific location.
However, my post / save event inserts into the table that the view is made from, containing all locations.
I am getting an error when I try to add the new event to the data connection.
"The field Location must be a string or array type with a maximum length of '1'." string
PropertyName "Location" string
I tried to set the string for the event manually before adding it to the data connection but this isn't working for some reason. Could it be me not declaring the string correctly?
//Actions for Calendar 5
public JsonResult GetEvents5()
{
using (CalgaryNEEntities dc = new CalgaryNEEntities())
{
var events = dc.CalgaryNEEvents.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent5(EventsAllLocation e)
{
var status = false;
using (InsertEntities dc = new InsertEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.EventsAllLocations.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
var locationstring = "Calgary NE Kitchens";
v.CompanyName = e.CompanyName;
v.Start = e.Start;
v.End = e.End;
v.KitchenNumber = e.KitchenNumber;
v.Location = locationstring;
}
}
else
{
var locationstring = "Calgary NE Kitchens";
e.Location = locationstring;
dc.EventsAllLocations.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
Here is the EventsAllLocation definition:
public partial class EventsAllLocation
{
public int EventID { get; set; }
public string Location { get; set; }
public string CompanyName { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string KitchenNumber { get; set; }
}
Any tips or help would be greatly appreciated, thanks!
The answer is staring you in the face !! LOL
"The field Location must be a string or array type with a maximum
length of '1'." string PropertyName "Location" string
Related
This is my javascript to load partial view by sending a data array as a parameter.
$('body').on('click', '.btn-add-answer', function () {
var answerObj = Array.from(GetAnswerDetails(this));
var lastAnswer = answerObj[answerObj.length - 1];
var answers = {};
answers.Id = parseInt(lastAnswer.Id) + 1;
answers.FormQuestionId = lastAnswer.FormQuestionId;
answers.Text = "";
answers.IsCorrect = false;
answers.Score = null;
answers.QuestionAnswerId = 0;
answers.Sequence = 0;
answerObj.push(answers);
$("#survey-answer-container")
.load("LoadTest", answerObj);
});
This is my controller
public ActionResult LoadTest(List<AnswerDto> answers)
{
return PartialView("_SurveyPageSectionQuestionAnswer", answers);
}
And this is my DTO
public class AnswerDto
{
public int Id { get; set; }
public string Text { get; set; }
public int Sequence { get; set; }
public bool? IsCorrect { get; set; }
public int? Score { get; set; }
public int FormQuestionId { get; set; }
public int QuestionAnswerId { get; set; }
}
The issue is the parameter didn't get to the controller. The 'answers' parameter in the controller will only have default values.
How to send data array from javascript as a parameter in partial view load?
Try your object like below. Wrap your object as { answers: answerObj } so it could match with parameter name.
$("#survey-answer-container")
.load("LoadTest", { answers: answerObj });
There's a javascript library called Crypto-js and i'm trying to convert some methods I use to c#.
For example in javascript:
var payload = JSON.stringify({ market: "BTC-ETH", order: { price: "0.02159338", side: "buy", size: "0.024" } });
var contentHash = cryptoJS.SHA512(payload).toString(cryptoJS.enc.Hex);
console.log(contentHash);
In C#
public class OrdersVM
{
public string Market { get; set; }
public Order Order { get; set; }
}
public class Order
{
public string Price { get; set; }
public string Side { get; set; }
public string Size { get; set; }
}
public async Task<IActionResult> Orders([FromBody] OrdersVM vm) {
var payload = JsonConvert.SerializeObject(vm);
var contentHash = sha512Hex(payload).ToLower();
Console.WriteLine(contentHash);
}
public string sha512Hex(string input)
{
var bytes = Encoding.UTF8.GetBytes(input);
using (var hash = SHA512.Create())
{
hash.ComputeHash(bytes);
return BitConverter.ToString(hash.Hash).Replace("-", "");
}
}
contentHash for javascript is
"99bb05af8aace509189e08625bb4e475a9daaafc92edf5c85fa1aefcc16c16e4533c23843c5806aef01c97e8cb4150b2dc129d04d3b6a50331833fe5cb8158fc"
and for c#
"731b92cf482ff90ffe759e356959ec005334062bdc3c2cc78b48c3041d21a45ecaa6b33f6df2971fa868f94f04b7596e818104cb1017ed1c436365beac3a01d1"
What am I doing wrong with c# conversion?
The issue is that JSON.Net, by default, will serialise your property names exactly as the appear, meaning they all start with a capital letter. There are two ways to fix this:
Using JsonProperty to explicitly control the property name serialisation. For example:
public class OrdersVM
{
[JsonProperty("market")]
public string Market { get; set; }
[JsonProperty("order")]
public Order Order { get; set; }
}
Use a contract resolver to tell JSON.Net how to process the names. Fortunately there is one provided for you that will do this:
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
var payload = JsonConvert.SerializeObject(vm, settings);
I have an api controller and a viewmodel as given below that fetch a set of records from an sql db and pass it to a razor view into a kendo grid.
Viewmodel:
public class SoonDueReportsViewModel
{
public SoonDueReportsViewModel()
{
}
public string ARAName { get; set; }
public int? ReportAraId { get; set; }
public string CompanyName { get; set; }
public int? CompanyId { get; set; }
public string ReportDetails { get; set; }
public DateTime? DueReportDate { get; set; }
public int ReportId { get; set; }
}
Controller:
public class AllDueReportsController : BaseApiController
{
private readonly IIdentityStorage identityStorage;
public IQueryable<SoonDueReportsViewModel> Get()
{
AppKatPrincipal appKatPrincipal = identityStorage.GetPrincipal();
var araIds = UnitOfWork.GetAll<UserGroup>()
.Where(group => group.Id == appKatPrincipal.GroupId)
.SelectMany(group => group.ARA).Select(ara => ara.Id);
var duties = UnitOfWork.GetAll<Duty>();
var companies = UnitOfWork.GetAll<Company>();
var aras = UnitOfWork.GetAll<ARA>().Where(x => araIds.Contains(x.Id));
var userGroupId = indireKatPrincipal.GroupId;
var userGroup = UnitOfWork.GetById<UserGroup>(userGroupId);
var foreRun = userGroup.ForRun.GetValueOrDefault();
var nextDate = DateTime.Today.AddMonths(foreRun); // The value of this variable I need to transport also to the view !!
var query = from ara in aras
join company in companies on ara.Id equals company.ARA
join duty in duties on company.Id equals duty.CompanyId
where duty.ReportedDate == null
&& company.Activ == true
select new SoonDueReportsViewModel
{
ARAName = ara.Name,
ReportAraId = ara.Id,
CompanyName = company.Name,
CompanyId = company.ID,
ReportDetails = duty.Details,
DueReportDate = duty.ReportDate,
ReportId = duty.Id,
};
return query;
}
}
Everything works fine, but in addition to the set of records (defined by the query) I also need to transport the value of the variable 'nextDate' to the same view.
If someone could give me a hint how to do this, I'd appreciate it a lot.
Regards, Manu
Background
I have an incomplete project built on MVC 5, EF 6 DB First & DevExpress extensions with following code spec (all original non-English variable names changed & entire code simplified to comply MCVE):
Model (Namespace: ProjectName.Models)
public class DBContext : DbContext
{
public DBContext : base("ConnectionStringName")
{
public DbSet<WinnerTable> Winners { get; set; }
public DbSet<UnitTable> Units { get; set; }
public DbSet<CustomerTable> Customers { get; set; }
}
}
[Table("WinnerTable")]
public class WinnerModel : IWinnerRepository
{
public String WinnerID { get; set; }
public String CustomerID { get; set; }
public String CustomerName { get; set; }
public String TranDate { get; set; }
public List<UnitModel> UnitList { get; set; }
public List<UnitModel> GetUnitList(String sessionID, DateTime tranDate)
{
// query to unit list
using (var DB = new DBContext())
{
var query = (from unit in DB.Units
where unit.SessionID == sessionID && unit.TranDate = tranDate
select new UnitModel()
{
// unit table to unit model definition
}).ToList();
return query;
}
}
}
[Table("UnitTable")]
public class UnitModel
{
public String UnitID { get; set; }
public String UnitName { get; set; }
// other definitions
}
Controller
using ProjectName.Models;
[RoutePrefix("Input")]
public class InputController : Controller
{
[HttpGet]
public ActionResult Winner()
{
WinnerModel model = new WinnerModel()
{
// default values on first visit/reload page
TranDate = DateTime.Now.Date,
UnitList = new List<UnitModel>(); // list declaration
}
return View(model);
}
public PartialViewResult CustomerData(String customerId, String sessionId, DateTime tranDate, WinnerModel model)
{
if (DevExpressHelper.IsCallback && !String.IsNullOrEmpty(customerId))
{
Session["CustomerID"] = customerId;
Session["SessionID"] = sessionId;
Session["TranDate"] = Convert.ToDateTime(tranDate);
using (var DB = new DBContext())
{
var query = DB.Customers.Where(c => c.CustomerID == customerId).FirstOrDefault();
// model property assignments
}
}
return PartialView("_CustomerData", model);
}
public PartialViewResult ShowItemsGrid(WinnerModel model)
{
String customerId = (Session["CustomerId"] ?? String.Empty).ToString();
String sessionId = (Session["SessionId"] ?? String.Empty).ToString();
String lastCustomer = (Session["LastCustomer"] ?? String.Empty).ToString();
DateTime tranDate = Convert.ToDateTime(Session["TranDate"] ?? DateTime.Now.Date);
using (var DB = new DBContext())
{
model.CustomerId = customerId;
model.SessionId = sessionId;
model.TranDate = tranDate;
model.UnitList = model.GetUnitList(sessionId, tranDate);
if (model.UnitList == null || model.UnitList.Count == 0)
{
model.UnitList = new List<UnitModel>();
}
Session["LastCustomer"] = lastCustomer;
return PartialView("_GridView", model);
}
}
}
View (Winner.cshtml)
#using ProjectName.Models
#model WinnerModel
#Html.EnableUnobtrusiveJavascript()
<script type="text/javascript">
var customer = null;
function initializeGrid()
{
ItemsGrid.PerformCallback(); // routine check if customer name exists
}
function comboChanged(s, e) {
customer = s.GetValue();
CustomerDataPanel.PerformCallback(); // callback to fill customer data for partial view & load units into gridview
}
// callback to insert values into session variable
function customerBeginCallback(s, e) {
e.customArgs["customerId"] = customer;
e.customArgs["sessionId"] = SessionId.GetValue();
e.customArgs["tranDate"] = TranDate.GetValue();
}
function customerEndCallback(s, e) {
ItemsGrid.PerformCallback();
}
// count checked data inside gridview
// this may be asked on other context and doesn't matter for this one
function countUnits(buttonName, url)
{
// other code
}
</script>
#using (Html.BeginForm("Winner", "Input", FormMethod.Post))
{
Html.DevExpress().TextBoxFor(m => m.SessionId, TextBoxSettings).GetHtml();
Html.DevExpress().DateEditFor(m => m.TranDate, DateEditSettings).GetHtml();
// this combobox has client-side event SelectedIndexChanged = "comboChanged"
// GetCustomers method just populate customers data into combobox and unrelated to this problem
Html.DevExpress().ComboBoxFor(m => m.CustomerId, ComboBoxSettings).BindList(ProjectName.Providers.GetCustomers()).GetHtml();
Html.RenderPartial("_CustomerData", Model); // DX callback panel
Html.RenderPartial("_GridView", Model);
// button to count all checked values inside gridview
Html.DevExpress().Button(CountButtonSettings).GetHtml();
Html.DevExpress().LabelFor(m => m.TotalPrice, PriceLabelSettings).GetHtml();
// button for submit & reset form here
Html.DevExpress().Button(SubmitButtonSettings).GetHtml();
Html.DevExpress().Button(ResetButtonSettings).GetHtml();
}
Partial View (_CustomerData.cshtml)
#using ProjectName.Models
#model WinnerModel
#{
// MVC DX callback panel for customer details
// Name = CustomerDataPanel
// CallbackRouteValues: Controller = Input, Action = CustomerData
// ClientSideEvents.BeginCallback = customerBeginCallback
// ClientSideEvents.EndCallback = customerEndCallback
Html.DevExpress().CallbackPanel(CallbackPanelSettings).GetHtml();
}
Partial View (_GridView.cshtml)
#using ProjectName.Models
#model WinnerModel
#{
// MVC DX GridView with row selection checkboxes
// The gridview column structure is exactly same as UnitModel has
// Name = ItemsGrid
// CallbackRouteValues: Controller = Input, Action = ShowItemsGrid
// ClientSideEvents.Init = initializeGrid
GridViewExtension grid = Html.DevExpress().GridView(GridViewSettings);
grid.Bind(Model.UnitList).GetHtml(); // grid bound to List<UnitModel>
}
All gridview changes require sufficent privileges (i.e. admin/supervisor).
Problem Statement
I want anyone help finding out where and how proper routine codes to empty gridview data must be attached on controller method(s) to give expected results. As I tried so far, the gridview still maintaining its previous state given from session variable when Winner page revisited or reloaded (immediate first visit after login worked because all session variables are empty, thus no data was populated to gridview).
Additionally, I want to show JS confirm message when user trying to close/reload Winner page while some/all gridview data are being checked.
Expected Results
For every first visit, revisit & reload on Winner page, the gridview content must empty.
After a user provides certain customer ID, the gridview will populated with some unit data from unit table, where changes inside it immediately lost when user accepts reloading/closing page confirm message.
Any kind of answers or suggestions will appreciated.
I am not understand this case:
I have a model like:
public class ExmDescobertos {
public int Id { get; set; }
public int ExameId { get; set; }
public int PlanoId { get; set; }
public int ConvenioId { get; set; }
}
And create an object javascript:
var objDescoberto = new Object();
objDescoberto.Id = $("#hdnDescobertoId").val(); //inputs with values...
objDescoberto.ExameId = $('#hdnExameId').val();
objDescoberto.PlanoId = $('#hdnPlanoId').val();
objDescoberto.ConvenioId = $('#hdnConvenioId').val();
And I am using Json.stringify(obj) to transmit the values with a $.post jQuery method:
var dados = JSON.stringify(objDescoberto);
In this point, dados is "{"Id":"27","ExameId":"53","PlanoId":"32","ConvenioId":"11"}", for example.
And have a controller with this action:
public PartialViewResult(ExmDescobertos descoberto) { }
But... the parameter in this controller not receive your values correct! :o
In this point descoberto is Id = 0; ExameId = 0; PlanoId = 0; ConvenioId = 0;
Not errors explicit, but not works...
Anybody have a idea of what I have missing?
Thank you for all!
Don't stringify you object, just send object as is.
$.post("/url", objDescoberto);
or
var dados = JSON.stringify({descoberto : objDescoberto});