Passsing a array in json and accessing it in controller of mvc - json

i am trying to make a array marklistdetails to post the mutliple students details, i am not able to access the same on controller, which is giving error as object not initialised
json code
var MarksEntry = {
Adm_Or_Name: '',
AdmissionNo: '',
Name: '',
ClassId: '',
ClassSectionId: '',
RollNo: '',
MarksEntered: '',
RemarksEntered: '',
Subjectid: '',
ExaminationID: '',
ExamDate: '',
Present: '',
MarksEntryDetails: [],
};
var MarksEntryDetails =
{
// StudentId: '',
MarksEntered: '',
// RemarksEntered: '',
// Total_Oral_Marks: '',
// TOTAL_PRACTICAL_MARKS: '',
//TOTAL_PROJECT_MARKS: '',
//TOTAL_MARKS: '',
// PRESENT: '',
// PASS_FAIL: '',
};
function SavingRecords(url) {
var result = 0;
var Index = 0;
//var marksEntrylist = [];
MarksEntry.ClassSectionId = $("table#IntialDetails tr").find("td").eq(6).html()
MarksEntry.ExaminationID = $("table#IntialDetails tr").find("td").eq(7).html()
MarksEntry.Subjectid = $("table#IntialDetails tr").find("td").eq(8).html()
$('table#student_marks tr').each(function () {
MarksEntry.MarksEntryDetails.add(new CreateMarksEntry(this));
console.log(MarksEntry.MarksEntryDetails);
$.getJSON(url,JSON.stringify(MarksEntry), function (data) {
Success = data;
});
// return Success
// alert(marksEntrylist);
//Index = $(this).index() + 1;
// MarksEntry.ExamDate = Formateddate;
// result = result + CreateMarksEntry(this);
});
if (result > 0) {
$("#Complete").html("No.of Records saved:" + result);
$("#Complete").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: true,
buttons: {
'Done': function () {
$(this).dialog('close');
var url = $("#RedirectTo").val();
location.href = url;
}
}
});
}
else {
alert('Records havent been saved');
}
function CreateMarksEntry(objTr) {
var cols = $(objTr).find('td');
// this.Name = $(cols[0]).html();
if ($(cols[4]).html() == " ") {
this.MarksEntered = "";
}
if ($(cols[5]).html() == " ") {
this.RemarksEntered = "";
}
var Details={
//this.RollNo = $(cols[1]).html();
//this.AdmissionNo = $(cols[2]).html();
MarksEntered: $(cols[4]).html(),
remarksentered: $(cols[5]).html()
}
// this.RemarksEntered = $(cols[5]).html();
// if (this.Name == " ") {
// this.Name = "";
// }
// if (this.RollNo == " ") {
// this.RollNo = "";
// }
// if (this.AdmissionNo == " ") {
/// this.AdmissionNo = "";
// }
if (this.MarksEntered == " ") {
this.MarksEntered = "";
}
if (this.RemarksEntered == " ") {
this.RemarksEntered = "";
}
// $.getJSON(url, MarksEntry, function (data) {
// Success = data;
// });
// return Success
};
}
model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Examination.Domain.ViewModel
{
public class vmStudentMarks
{
public string ExamTypeDesc { get; set; }
public int Subjectid { get; set; }
public int ClassSectionID { get; set; }
public string ExamDate { get; set; }
public int ExaminationID { get; set; }
public int Id { get; set; }
public string SchoolId { get; set; }
public string SessionId { get; set; }
public string Name { get; set; }
public string AdmissionNo { get; set; }
public string RollNo { get; set; }
public string Written { get; set; }
public string Oral { get; set; }
public string Practical { get; set; }
public string PASS_FAIL { get; set; }
public string Project { get; set; }
public string RemarksEntered { get; set; }
public string MarksEntered { get; set; }
public string ClassSection { get; set; }
public string SubjectName { get; set; }
public string StudentId { get; set; }
public long EXAM_RESULT_ID{ get; set; }
public long EXAM_RESULT_DET_ID { get; set; }
public int MAX_MARKS { get; set; }
public bool Present { get; set; }
public int ENTRY_USER_ID { get; set; }
public int UPDATE_USER_ID { get; set; }
public int GRACE { get; set; }
//public MarksEntryDetails[] #List { get; set; }
public List<MarksEntryDetails> MarksEntryDetails { get; set; }
}
public class MarksEntryDetails
{
public string StudentId { get; set; }
public string MarksEntered { get; set; }
public string remarksentered { get; set; }
public int total_oral_marks { get; set; }
public int total_practical_marks { get; set; }
public int total_project_marks { get; set; }
public int total_marks { get; set; }
public int present { get; set; }
public string pass_fail { get; set; }
public int grace { get; set; }
}
}
controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult CreateRecords(vmStudentMarks MarksEntry)
{
MarksEntry.MarksEntryDetails[0].MarksEntered.ToString();//error throws as object not intialised
UserProfile userProfile = SchoolSession.CurrentUser;
int Sucess = examScoreService.PostMARKSENTRYDETAILS(userProfile.School.Id, userProfile.CurrentSession.Id,
userProfile.EmployeeId,MarksEntry);
return Json(Sucess, JsonRequestBehavior.AllowGet);
}

You can use JSON.stringify when you posting data to pass arry of objects to controller.
$.ajax(
{
url: 'controller/CreateRecords',
data: JSON.stringify({MarksEntry: MarksEntry}),
contentType: 'application/json',
dataType: 'json',
type: 'POST',
success: function (data) {
// success
},
error: function () {
// error
}
});
Please refer following post for more information.
Pass Complex JavaScript Object to MVC Controller
It illustrates how we can pass complex javascript objects to MVC controller.
Thanks !

Related

Xamarin Forms Json Desrialization

I want to deserialize a JSON coming from a web service, but for some reason I am getting an exception. I searched every question related to this topic but I did not find anything related to this exception. What might me the problem? here is the exception:
Newtonsoft.Json.JsonSerializationException: 'Unexpected token while deserializing object: EndObject. Path '', line 1, position 243.'
Here is my deserialize method:
public async Task<LoginApiResponse> AuthenticateUserAsync(string username, string password)
{
// try
// {
LoginApiRequest loginRequest = new LoginApiRequest()
{
Username = username,
Password = password
};
// serialize object to json
var content = new StringContent(JsonConvert.SerializeObject(loginRequest), Encoding.UTF8, "application/json");
var response = await Client.PostAsync(Constants.LOGIN_URI, content);
response.EnsureSuccessStatusCode();
// get the data on success and serialize it from json
using (var stream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
using (var json = new JsonTextReader(reader))
{
System.Diagnostics.Debug.Write(">>>>>>>>>>>>>>>>>>>> " + Serializer.Deserialize<LoginApiResponse>(json));
return Serializer.Deserialize<LoginApiResponse>(json);
}
// }
/* catch (Exception ex)
{
return null;
}*/
}
here is the Request model:
public class LoginApiRequest
{
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
public LoginApiRequest() { }
}
here is the Response Model:
public class LoginApiResponse : MessageStatus
{
[JsonProperty("Data")]
public User Data { get; set; }
public LoginApiResponse() { }
}
here is the User model:
public class User
{
[JsonProperty("Address")]
public string Address { get; set; }
[JsonProperty("BloodType")]
public string BloodType { get; set; }
[JsonProperty("ConfirmPassword")]
public string ConfirmPassword { get; set; }
[JsonProperty("CustomerID")]
public string CustomerID { get; set; }
[JsonProperty("DOB")]
public string DOB { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("ID")]
public int? ID { get; set; }
[JsonProperty("IsActive")]
public bool IsActive { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
[JsonProperty("Phone")]
public string Phone { get; set; }
[JsonProperty("UserRoleID")]
public int? UserRoleID { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
public User() { }
}
and here is the the messagestatus:
public class MessageStatus
{
[JsonProperty("Message")]
public string Message { get; set; }
[JsonProperty("Status")]
public int Status { get; set; }
public MessageStatus() { }
}
and finally here is the json:
{
"Message": null,
"Status": 1,
"Data": {
"Address": "Beirut",
"BloodType": null,
"ConfirmPassword": null,
"CustomerID": null,
"DOB": null,
"Email": null,
"ID": 22,
"IsActive": true,
"Name": "tg",
"Password": "123456",
"Phone": "03708424",
"UserRoleID": 1,
"Username": "tg"
}
}
instead of
using (var stream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
using (var json = new JsonTextReader(reader))
{
System.Diagnostics.Debug.Write(">>>>>>>>>>>>>>>>>>>> " + Serializer.Deserialize<LoginApiResponse>(json));
return Serializer.Deserialize<LoginApiResponse>(json);
}
try
var json = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<LoginApiResponse>(json)
return data;

How make dropdownlist to access data on your SelectItemList using asp.net mvc?

I am using DropDownlist in order to get country of all the world. I have attached the file(country_list.txt) using srcFilePath. The error i am getting is "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCountryId'.What could be an issue, because my EditFormTrainingRegViewModel does have this field SelectedCountry as a primary key. Its been declared as public int? SelectedCountryId {get;set;}
// List for countries.
private IEnumerable<SelectListItem> GetCountryList()
{
SelectList listcn = null;
try
{
var list = this.LoadData().Select(p => new SelectListItem
{
Value = p.Country_Id.ToString(),
Text = p.Country_Name
});
listcn = new SelectList(list, "Value", "Text");
}catch(Exception ex)
{
throw ex;
}
return listcn;
}
public ActionResult DropDownSelect()
{
EditTrainingRegFormViewModel model = new EditTrainingRegFormViewModel();
model.SelectedCountryId = 0;
this.ViewBag.CountryList = this.GetCountryList();
return this. View(model);
}
// Loading data for country list.
private List<EditTrainingRegFormViewModel> LoadData()
{
List<EditTrainingRegFormViewModel> lst = new List<EditTrainingRegFormViewModel>();
try
{
string line = string.Empty;
string srcFilePath = "Content/files/country_list.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader src = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
// while to read the file
while((line = src.ReadLine()) !=null) {
EditTrainingRegFormViewModel infoLst = new EditTrainingRegFormViewModel();
string[] info = line.Split(',');
//Setting
infoLst.Country_Id = Convert.ToInt32(info[0].ToString());
infoLst.Country_Name = info[1].ToString();
lst.Add(infoLst);
}
src.Dispose();
src.Close();
}catch(Exception ex)
{
Console.Write(ex);
}
return lst;
}
//View
#Html.DropDownListFor(m=>m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new {#class = "form-control"})
// Model class
public class EditTrainingRegFormViewModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public string Company { get; set; }
public string Address { get; set; }
[Display(Name = "Choose country")]
public int ? SelectedCountryId { get; set; }
public string Code { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Cell_Number { get; set; }
public List<string> Dietary_requirement { get; set; }
public string Email { get; set; }
public int Country_Id { get; set; }
public string Country_Name { get; set; }
}

How to create multiple Radiobutton group in ASP.Net Core 2 and Razor?

I want to create multiple grouped Radio buttons. So, basically I have multiple questions and 3 radio buttons with answers. The problem I'm facing is how to return the selected value for the multiple radio buttons.
Controller
public IActionResult Test()
{
SafetyObservationCardForm form = new SafetyObservationCardForm();
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
var questions = dbConnection.Query<QuestionsViewModel>("SELECT * FROM SOCQuestions ORDER BY soc_order_id");
var observationType = new List<ObservationType>
{
new ObservationType { Id = 1, Name = "Safe" },
new ObservationType { Id = 2, Name = "At Risk" },
new ObservationType { Id = 3, Name = "N/A" }
};
var rb = new List<Answer>();
foreach (var item in questions)
{
rb.Add(new Answer { Id = item.soc_question_id, ObservationTypes = observationType });
};
form.Answers = rb;
form.Questions = questions.ToList();
return View(form);
}
}
Model
public class SafetyObservationCardForm
{
public List<QuestionsViewModel> Questions { get; set; }
public string Comments { get; set; }
public string Location { get; set; }
public string Observer { get; set; }
public DateTime TimeStamp { get; set; }
public string Task { get; set; }
public ObserverType ObserverType { get; set; }
public IEnumerable<Answer> Answers { get; set; }
}
public class ObserverType
{
public bool Supervisor { get; set; }
public bool Peer { get; set; }
public bool Self { get; set; }
public bool Other { get; set; }
}
public class ObservationType
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Answer
{
public int Id { get; set; }
public IEnumerable<ObservationType> ObservationTypes { get; set; }
public int SelectedObservation { get; set; }
}
}
View
Here I'm trying the loop. Answers model is null when I submit the form for some reason.
#model DBI.Safety.Models.SafetyObservationCardForm
<form asp-action="CreateTest">
#foreach (var answer in Model.Answers)
{
<input name="#answer.Id" asp-for="#answer.SelectedObservation" type="radio"
value="#answer.Id" /> #answer.ObservationTypes
}
</form>

How to use Postback in ASP.net MVC

How to preserve the selected value after postback for that dropdownlist?
I have used two dropdown lists in my application. I need to search the gridview data based on the selected values of dropdownlist. The searched data is displayed in the pagedlist format. But when i move to next page of pagedlist, its displaying the whole grid view data rather than searched data. so any help will be appreciated.
My Model
namespace CCIOfficeServiceManagementSystem.Models
{
public class AirtelManagementModel
{
public long MobileAcNumber { get; set; }
public long AirtelNumber { get; set; }
public int OneTime { get; set; }
public float MonthlyCharges { get; set; }
public float CallCharges { get; set; }
public float ValueAddedServices { get; set; }
public float MobileInternetUsage { get; set; }
public float Roaming{ get; set; }
public float Discounts { get; set; }
public float Taxes { get; set; }
public float TotalCharges { get; set; }
public string WhoUploaded { get; set; }
public DateTime UploadedDate { get; set; }
public DateTime DateOfCreation { get; set; }
public int ImportDateId { get; set; }
public List<MonthListClass> MonthList
{
get;
set;
}
public List<clsYearOfDate> YearList
{
get;
set;
}
}
public class MonthListClass
{
public int MonthSelectedId { get; set; }
public string MonthName { get; set; }
}
public class clsYearOfDate
{
public int YearSelectedId { get; set; }
public string YearOfDate { get; set; }
}
}
My View
#using (Html.BeginForm("ViewDataOfDatabase", "AirtelManagement",FormMethod.Post))
{
<h3>Search by PhoneNumber:#Html.TextBox("SearchString",ViewBag.CurrentFilter as string)</h3>
<p><h3>Year:#Html.DropDownList("Yearitems", (IEnumerable<SelectListItem>)ViewBag.SelectList, "Select Year")</h3>
<h3>Month:#Html.DropDownList("MonthItems", (IEnumerable<SelectListItem>)ViewBag.SelectMonthList, "Select Month")</h3>
<h3>City: #Html.DropDownList("CityNames", (IEnumerable<SelectListItem>)ViewBag.CityList, "Select City")</h3></p>
<p><input type="submit" value="Search" /></p>
<script>
$(document).ready(function () {
$("#Yearitems").change(function () {
//debugger;
//alert($("#Yearitems>option:selected").attr("Value"));
$.ajax({
type: "Post",
url: '#Url.Action("GetMonths","AirtelManagement")',
data: { YearId: $("#Yearitems>option:selected").attr("Value") },
datatype: "Json",
success: function (data) {
//debugger;
$("#MonthItems").html("");
$.each(data, function (index, item) {
$("#MonthItems").append(new Option(item.MonthName, item.MonthSelectedId));
});
},
error: function () {
alert("Select Year");
}
});
});
});
</script>
My controller's action Method
public ActionResult ViewDataOfDatabase(string sortorder, string currentFilter, string searchString, int? page,FormCollection collection)
{
CCIRepository _repository = CCIRepository.CreateRepository();
AirtelManagementModel _Airtelmodel = new AirtelManagementModel();
IEnumerable<CityListClass> CityList = _repository.GetCities();
IEnumerable<SelectListItem> CityListItems = from c in CityList
select new SelectListItem()
{
Value = c.CityName.ToString(),
Text = c.CityName.ToString(),
Selected = c.CityName == Request["CityNames"],
};
ViewBag.CityList = CityListItems;
IEnumerable<clsYearOfDate> SelectList = GetYears();
//IEnumerable<MonthListClass> SelectMonthList = GetMonths(YearId);
IEnumerable<SelectListItem> Yearitems = (from v in SelectList
select new SelectListItem()
{
Value = v.YearSelectedId.ToString(),
Text = v.YearOfDate.ToString(),
Selected = v.YearOfDate == Request["Yearitems"],
});
ViewBag.SelectList = Yearitems;
int DateId=0;
string CityName = string.Empty;
try
{
int SelectedYear = Convert.ToInt16(collection["Yearitems"].ToString());
int SelectedMonth = Convert.ToInt16(collection["MonthItems"].ToString());
CityName = collection["CityNames"].ToString();
DateId = _repository.GetImportDateId(SelectedYear, SelectedMonth);
}
catch(NullReferenceException Ex)
{
}
//IEnumerable<SelectListItem> MonthItems = (from m in SelectMonthList
// select new SelectListItem()
// {
// Value = m.MonthSelectedId.ToString(),
// Text = m.MonthName,
// });
//ViewBag.SelectMonthList = MonthItems;
IEnumerable<SelectListItem> MonthItems = Enumerable.Empty<SelectListItem>();
ViewBag.SelectMonthList = MonthItems;
List<AirtelManagementModel> list = ViewDetails();
ViewBag.CurrentSort = sortorder;
ViewBag.PhoneSortParm = String.IsNullOrEmpty(sortorder) ? "Phone_desc" : "";
if (searchString != null )
{
page = 1;
}
else
{
searchString = currentFilter;
}
//if(searchString!=null)
//{
ViewBag.CurrentFilter = searchString;
var airteldetails = from _model in list
select _model;
if(!String.IsNullOrEmpty(searchString) && DateId!=0 && !String.IsNullOrEmpty(CityName))
{
airteldetails = _repository.FilterAirtelDetails(searchString, DateId, CityName);
int PageSize = 5;
int PageNumber = (page ?? 1);
return View(airteldetails.ToPagedList(PageNumber, PageSize));
}
//airteldetails=airteldetails.OrderByDescending(A=>A.AirtelNumber);
int pageSize = 5;
int pageNumber = (page ?? 1);
//return View(airteldetails.ToList());
return View(airteldetails.ToPagedList(pageNumber, pageSize));
//}
//if (list.Count > 0)
//{
// var airteldetails = from _model in list
// select _model;
// return View(airteldetails.ToPagedList(pageNumber,pageSize));
//}
//else
//{
// ModelState.AddModelError("Error", "No Data found in Database");
// return RedirectToAction("ImportExcelFile", "AirtelManagement");
//}
}

KeyNotFoundException on SaveChanges()

Okey so i'm trying to update information in my database from a form.
But when i call db.SaveShanges() i get KeyNotFoundException.
I'm using MVC3 and EF 4.1.
I use Controller->Service->Repositry->EF design pattern.
The callstack:
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Data.Objects.EntityEntry.UpdateComplexObjectSnapshot(StateManagerMemberMetadata member, Object userObject, Int32 ordinal, Object currentValue)
at System.Data.Objects.EntityEntry.DetectChangesInProperties(Boolean detectOnlyComplexProperties)
at System.Data.Objects.ObjectStateManager.DetectChangesInScalarAndComplexProperties(IList`1 entries)
at System.Data.Objects.ObjectStateManager.DetectChanges()
at System.Data.Objects.ObjectContext.DetectChanges()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate)
at System.Data.Entity.Internal.InternalContext.GetStateEntries()
at System.Data.Entity.Infrastructure.DbChangeTracker.Entries()
at System.Data.Entity.DbContext.GetValidationErrors()
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
My repositrory db is a dbContext with a DbSet for the model i'm using.
public bool Save()
{
try
{
db.SaveChanges();
}
catch(Exception e)
{
return false;
}
return true;
}
My Service that calls the repository
public bool UpdateUserInformationFromSettingsModel(UserSettingsModel model)
{
int userInfoID = _profile.GetUserInformationID(model.userName);
UserInformation userInfo = _repository.Get(userInfoID);
if (userInfo == null)
{
return false;
}
userInfo.firstName = model.firstName;
userInfo.lastName = model.lastName;
userInfo.phone = model.phone;
userInfo.invoiceReciever = model.invoiceReciever;
userInfo.invoiceAddress = model.invoiceAddress;
userInfo.address = model.address;
userInfo.preferedLanguage = model.preferedLanguage;
bool saveSuccess = _repository.Save();
if(!saveSuccess)
{
return false;
}
return true;
}
My controller
[HttpPost]
public ActionResult Edit(UserSettingsModel model)
{
if(ModelState.IsValid)
{
if (_userService.UpdateUserInformationFromSettingsModel(model))
{
return RedirectToAction("Settings");
}
ModelState.AddModelError("", GuiText.editSettingsError);
}
return View(model);
}
The UserInformation Model
public class UserInformation
{
public int ID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string phone { get; set; }
public string invoiceSendOption { get; set; }
public string invoiceReciever { get; set; }
public Address invoiceAddress { get; set; }
public Address address { get; set; }
public string preferedLanguage { get; set; }
public string confirmCode { get; set; }
public UserSiteSettings siteSettings { get; set; }
public UserInformation()
{
firstName = "";
lastName = "";
phone = "";
invoiceSendOption = "";
invoiceReciever = "";
invoiceAddress = new Address();
address = new Address();
preferedLanguage = "";
confirmCode = "";
siteSettings = new UserSiteSettings();
}
The UserSettingsModel
public class UserSettingsModel
{
public string userName { get; set; }
[Display(Name = "name", ResourceType=typeof(GuiText))]
public string firstName { get; set; }
public string lastName { get; set; }
[Display(Name = "phone", ResourceType = typeof(GuiText))]
public string phone { get; set; }
[Display(Name = "invoiceInfo", ResourceType = typeof(GuiText))]
public string invoiceReciever { get; set; }
public Address invoiceAddress { get; set; }
[Display(Name = "address", ResourceType = typeof(GuiText))]
public Address address { get; set; }
[Display(Name = "prefLang", ResourceType = typeof(GuiText))]
public string preferedLanguage { get; set; }
public List<SelectListItem> preferedLanguageList { get; set; }
I have checked the variables in debugger and it all seems to be ok.
I'm using MySql connector v6.5.4.
So anyone got any ideas what the problem might be?
After some days of frustration and searching i found the problem.
I used a custom made equals method in my UserInformation and Address class. That caused the problems. Now i have removed it and changed my Unit Tests to work in another way.