ASP.NET MVC Javascript Inserting Indexed Fields Into a List - javascript

I am trying to create a simple survey application and I am experiencing trouble accessing the survey's questions.
Survey Model
public class Survey
{
public Survey()
{
Questions = new List<Question>();
CompletedBy = new List<CompletedSurveys>();
}
public int SurveyID { get; set; }
public string Name { get; set; }
public List<Question> Questions { get; set; }
}
Question Model
public class Question
{
public int QuestionID { get; set; }
public int SurveyID { get; set; }
public string Title { get; set; }
}
And I auto generate input fields for the questions using the code below:
<input type="hidden" name="Questions['+ itemIndex +'].QuestionID"></input>
Which renders to:
<input type="hidden" name="Questions[0].QuestionID">
What am I doing wrong? It seems like I am inserting the questions into the list incorrectly. Since my model's questions are always null.
Any guidance would be greatly appreciated.

You don't need to JavaScript for generating hidden fields in this case. You can do it with a loop and #Html.Hidden like this:
for(int i = 0; i < Model.Questions.Count; i++)
{
#Html.Hidden(Model.Questions[i].QuestionID.ToString())
}

Related

HighChart in ASP.NET MVC with Database connection

I am very new to ASP.NET MVC and I attempting to display data from a database into a Highchart using Visual Studio 2015. I have the following code in my controller to get the data from the database:
namespace HelloWorld.Controllers
{
public class SecondlyReadingDatasController : ApiController
{
private cloudsqlEntities db = new cloudsqlEntities();
// GET: api/SecondlyReadingDatas
public IQueryable<SecondlyReading> GetSecondlyReadings()
{
SecondlyReading sec = db.SecondlyReadings.First();
return db.SecondlyReadings;
}
This is my model:
namespace HelloWorld.Models
{
using System;
using System.Collections.Generic;
public partial class SecondlyReading
{
public int Id { get; set; }
public int ChannelID { get; set; }
public string TimeStamp { get; set; }
public double RMSVoltage { get; set; }
public double Frequency { get; set; }
public double RMSCurrent { get; set; }
public double RealPower { get; set; }
public double ReactivePower { get; set; }
public double ApparentPower { get; set; }
public double PowerFactor { get; set; }
public string DeviceId { get; set; }
}
}
I can get data in json format when I key in /api/SecondlyReadingDatas into my browser, however, my objective is to have that data to be plot into a line graph using high chart. I do know that something like the following code needs to be implemented to view the data in a line graph:
<script type="text/javascript">
$.ajax({
url: 'http://localhost/TestWebsite/api/SecondlyReadingDatas',
success: function(singleSeries) {
Highcharts.chart('container', {
series: [singleSeries]
});
}
});
</script>
I have also installed DotNet.HighChart in my project:
I have 2 main questions:
Is there a difference downloading the Highchart library from the
website, which will then be referenced in Visual Studio and
installing DotNet.HighChart in Visual Studio itself?
In which file do I place the <script type="text/javascript"> ?
Model, controller, or _Layout.cshtml?
Question 1
DotNet.HighCharts package is includes js files that You can use them depending on the application.
Question 2
You always should add <script type="text/javascript"> in View (client side). Model and Controller are used for server side.
See this article for more information about Highcharts in ASP.NET MVC.

.ParentTaskIdMapping properties in gantt of syncfusion does not work?

I am using Syncfusion Essential Studio Edition Version 14.2.0.28 . When i am working with gantt chart and want to indent subtask/subsession inside of parent task/session then it does not work.I followed bellow link
https:
//help.syncfusion.com/aspnetmvc/gantt/data-binding?cs-save-lang=1&cs-lang=csharp
Self-Referential Data Binding (Flat Data)
but till now does not work any one can suggest me? I shared 2 screen shot please follow
Real Data where data displayed without parent child indentation
Gantt Code snippet
To render the Gantt using Self Reference data source we need to consider the following things.
TaskId should be unique.
ParentId should be null for the parent Item.
For child items its parentId should be similar to its
relevant parent item’s task id.
We need to map the taskId field in “taskIdMapping” and parentId using “parentTaskIdMapping”.
Please find our online demo sample for your reference
Sample: http://mvc.syncfusion.com/demos/web/gantt/ganttselfreference
Regards,
Syncfusion Team
Syncfusion Team, Finally I solved the problem that i faced.When i am using your sample Code from gantt-> Data Binding -> Self Referencial Data Binding(Flat Data) Sample Code.
It seems to me where you need to do this correction.According to your example.
Syncfusion Sample Code Snippet:
public class Data
{
public string StartDate { get; set; }
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public int Duration { get; set; }
public int PercentDone { get; set; }
public List<Data> Children { get; set; }
public string Predescessor { get; set; }
}
The Change I made to make workable this sample is
public class Data
{
public string StartDate { get; set; }
public int Id { get; set; }
***public int? ParentId { get; set; }***
public string Name { get; set; }
public int Duration { get; set; }
public int PercentDone { get; set; }
public List<Data> Children { get; set; }
public string Predescessor { get; set; }
}

How to implement previous and next button using ajax in mvc?

I am building an online test webapp in asp.net mvc4.And I need to make the user to navigate between previous and next questions (only 1 question at a time). I have a layout which has a countdown timer in it. I have a question & options list as a model in the view and I need to navigate the list via previous and next buttons. The layout must remain same since it has a timer in it. When the user clicks on 'next', the current question should get back to list along with chosen answer (via radio buttons) and the next question from the list should be displayed. Similar function is done by previous button also. Can anyone please suggest a solution in Ajax,Json or Javascript ?
The view:StartTest
#model LoginTrial3.Models.QuestionPaper
#{
ViewBag.Title = "StartTest";
Layout = "~/Views/Shared/_LayoutTest.cshtml";
}
<h2>StartTest</h2>
Model : QuestionPaper
public class QuestionPaper
{
public List<object> RandomQuestionList = new List<object>();
//generate the maps to hold the answers
public Dictionary<int, string> AptiAnsList = new Dictionary<int, string>();
public Dictionary<int, string> TechAnsList = new Dictionary<int, string>();
//define a ctor
public QuestionPaper(List<object> QList)
{
foreach(var item in QList)
{
RandomQuestionList.Add(item);
}
}
}
each object in QList is of a AptiQuestionType :
public class AptiQuestion
{
public int Id { get; set; }
public string Question { get; set; }
public string OptionA { get; set; }
public string OptionB { get; set; }
public string OptionC { get; set; }
public string ExpectedAnswer { get; set; }
}
A solution without ajax could be to extend the model class and add ids of the previous and next items, then in the view render links using these ids.

Reading NewtonSoft Json Data with Jquery/Javascript

I am facing problem while using the object that i have sent from my controller to view using Json.
I am sending List of Objects to the View by using NewtonSoft.Json 7.x.x to serialize the List to Json. I am using the below code to serialize:
return JsonConvert.SerializeObject(DataToSend, Formatting.None, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
I have 2 Entity Classes:
1) Form
2) FormFields
There is a 1-to-Many Relationship between these 2 entities.
public class Form
{
public long ID { get; set; }
public string Name { get; set; }
public virtual List<FormField> FormFields { get; set; }
}
public class FormField
{
public long FormID { get; set; }
public string FieldLabel { get; set; }
public string FieldType { get; set; }
public string FieldValue { get; set; }
public virtual Form form { get; set; }
}
I am trying to send the List of FormField to the view for rendering using Javascript. I am able to send it using the above serializaton Method.
But the problem is that, When i receive the Array of Objects in Javascript. It has Json Reference object IDs. I am not able to access those objects normally.
I am able to render the 1st FormField value in that array but i am not able to render rest of them. It is coming as Undefined.
I am attaching a screenshot of JSON Object Values which i am receiving on UI. You can see that there is an Object array. Each Object should have the Object of Type FormField and should have that field's value but there isn't.
Only the Object at index 0 is having the values and Rest of the Indexes have only Reference IDs.
Please help me resolve it.
Thanks
I don't know, if it is the best solution or not but I am posting so that may be it can save someone else's struggle to find the solution.
I Managed to do it using the .NET extension library plugin. Instead of using Newtonsoft.Json, I used System.Web.Extension DLL.
I put the attribute ScriptIgnore in my models as:
public class Form
{
public long ID { get; set; }
public string Name { get; set; }
[ScriptIgnore]
public virtual List<FormField> FormFields { get; set; }
}
public class FormField
{
public long FormID { get; set; }
public string FieldLabel { get; set; }
public string FieldType { get; set; }
public string FieldValue { get; set; }
[ScriptIgnore]
public virtual Form form { get; set; }
}
Then, I serialized it with the System.Web.Script.Serialization.JavaScriptSerializer as:
return new JavaScriptSerializer().Serialize(DataToSend);
It will serialize all the data but it will ignore the Properties which are having the attribute ScriptIgnore and it won't try to serialize them. For me it worked as required.
Just came to know that there is an Attribute JsonIgnore provided by NewtonSoft.Json that does the same job as ScriptIgnore. So, If you are using NewtonSoft Library then you can also use this.
It's good to know there are more ways to achieve the same result ;)

Getting the error: JavaScript runtime error: Circular reference in value argument not supported

When trying to edit and save a record in an ajax call via javascript, I am getting the above subject error.
I did some looking up, and the only thing I can find was something about a "compareByIdentity" property which I couldn't get how to implement in my situation, if that's the case.
The below class is where there is a one to many relationship. There can be one "project" to many "timetrackings". This is the class for the "TimeTrackings" where the "ProjectID" is the foreign key.
I am using a WCF application to retrieve and edit the data with EF 6. This is the first time I'm encountering it in my application. Obviously, because of the way the relationship is set up.
Can someone please inform me how I can correct this error?
namespace YeagerTechDB.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
[Serializable, DataContract(IsReference = true)]
public partial class TimeTracking
{
[Key]
[ScaffoldColumn(false)]
[Editable(false)]
[Display(Name = "Tracking ID")]
[DataMember]
public int TimeTrackingID { get; set; }
[Required]
[Display(Name = "Project ID")]
[DataMember]
public short ProjectID { get; set; }
[Required]
[DataType(DataType.Date)]
[DataMember]
public DateTime StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
[DataMember]
public DateTime EndDate { get; set; }
[DataType(DataType.MultilineText)]
[DataMember]
public string Notes { get; set; }
[DataType(DataType.DateTime)]
[DataMember]
public DateTime CreatedDate { get; set; }
[DataType(DataType.DateTime)]
[DataMember]
public DateTime? UpdatedDate { get; set; }
[DataMember]
public virtual Project Project { get; set; }
}
}
The output of the debugging is below. Please copy the image and paste it to your favorite image viewer for better detail.
Notice that the value of the TimeTrackingID is set correctly to 1.
The problem is coming from your JSON.stringify in line 66.
You are converting the object Tracking_Input to json.
Tracking_Input.TimeTrackingID is a jquery array of dom elements with the id TimeTrackingID, and this cannot be converted to json.
Did you mean $('TimeTrackingID').val() to match the other lines

Categories