why I see validation messages before form submiting - razor

I've created a form and when I load the page with it I see validation messages before I submit the form. Why? You can download my code from github
The similar question. It's because of mvc4
#model MyMustAgreeValidation.Models.NewUserProfileModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
#Html.MyEditFor(m=>m.Login)
#Html.MyEditFor(m=>m.Password)
#Html.MyEditFor(m=>m.ConfirmPassword)
#Html.MyEditFor(m=>m.DisplayName)
#Html.MyEditFor(m=>m.Email)
#Html.MyEditFor(m=>m.Homepage)
#Html.MyEditFor(m=>m.AgreementAccepted)
<p><input type="submit" value="#CreateRes.CreateProfileButton"/></p>
</fieldset>
}
Where Html.MyEditFor is
public static MvcHtmlString MyEditFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
return html.Partial("Item", new LabelEditorValidation() { Label = html.LabelFor(expression), Editor = html.EditorFor(expression), Validation = html.ValidationMessageFor(expression) });
}
And Item is partial view:
#model MyMustAgreeValidation.Models.LabelEditorValidation
<div class="editor-label">
#Model.Label
</div>
<div class="editor-field">
#Model.Editor
#Model.Validation
</div>
LabelEditorValidation:
public class LabelEditorValidation
{
public MvcHtmlString Label { get; set; }
public MvcHtmlString Editor { get; set; }
public MvcHtmlString Validation { get; set; }
}
Scripts included:
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/Validation/EqualAttribute.js"></script>
Form model NewUserProfileModel:
public class NewUserProfileModel : UserProfileModel, IValidatableObject
{
[Display(Name="Password", ResourceType = typeof(NewUserProfileRes))]
[DataType(DataType.Password)]
[Required(ErrorMessageResourceName = "FieldIsRequired", ErrorMessageResourceType = typeof(ErrorsRes))]
[StringLengthRange(6, 64, ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "InvalidStringLength")]
public string Password { get; set; }
[Display(Name="ConfirmPassword", ResourceType = typeof(NewUserProfileRes))]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessageResourceType = typeof(NewUserProfileRes), ErrorMessageResourceName = "PasswordsDontMatch")]
public string ConfirmPassword { get; set; }
[Display(Name="AgreementAccepted", ResourceType = typeof(NewUserProfileRes))]
[Equal(true, ErrorMessageResourceType = typeof(NewUserProfileRes), ErrorMessageResourceName = "MustAgreeWithEULA")]
public bool AgreementAccepted { get; set; }
public NewUserProfileModel()
{
var property = GetType().GetProperty("Login");
var list = property.GetCustomAttributes(true);
foreach (var item in list)
{
Console.WriteLine(item);
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var userRepository = new UserRepository();
if (userRepository.IsLoginExists(Login))
{
yield return new ValidationResult(NewUserProfileRes.LoginAlreadyExists, new []{"Login"});
}
}
UserProfileModel:
public class UserProfileModel
{
[Display(Name = "Login", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.Text)]
[Required(ErrorMessageResourceName = "FieldIsRequired", ErrorMessageResourceType = typeof(ErrorsRes))]
[StringLengthRange(3, 64, ErrorMessageResourceName = "InvalidStringLength", ErrorMessageResourceType = typeof(ErrorsRes))]
public string Login { get; set; }
[Display(Name="DisplayName", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.Text)]
[Required(ErrorMessageResourceName = "FieldIsRequired",
ErrorMessageResourceType = typeof(ErrorsRes))]
[StringLengthRange(3, 32,
ErrorMessageResourceName = "InvalidStringLength",
ErrorMessageResourceType = typeof(ErrorsRes))]
public string DisplayName { get; set; }
[Display(Name = "Email", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.EmailAddress)]
[Required(ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "FieldIsRequired")]
[RegularExpression(#"[\w\.-]*[a-zA-Z0-9_]#[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]", ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "InvalidEmailAddress")]
[StringLength(64, ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "StringTooLong")]
public string Email { get; set; }
[Display(Name="Homepage", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.Url)]
[RegularExpression(#"(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?", ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "IvalidUrl")]
[StringLength(96,
ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "StringTooLong")]
public string Homepage { get; set; }
}
EqualAttribute.js:
jQuery.validator.addMethod("equal", function (value, element, param) {
if($(element).attr("type")=="checkbox")
{
value = String($(element).attr("checked"));
param = param.toLowerCase();
}
return (value == param);
});
jQuery.validator.unobtrusive.adapters.addSingleVal("equal", "valuetocompare");

Related

RestSharp query returning NotFound

This is my first usage of RestSharp
I am trying to connect to HubSpot using their FormsAPI (https://legacydocs.hubspot.com/docs/methods/forms/submit_form)
Using .Net, C#, MVC.
When I run in Fiddler, it works.
Here is my C# code, when I run it, I get a StatusCode of "NotFound". I am sure it is something simple I am missing?
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest("submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
request.AddUrlSegment("portalId", "[myportalid]");
request.AddUrlSegment("formGuid", "[myformid]");
request.AddQueryParameter("hapikey", "[myapikey]");
request.RequestFormat = DataFormat.Json;
request.AddParameter("firstname", "testfirstname");
request.AddParameter("lastname", "testlastname");
request.AddParameter("email", "testemail#emailaddress.com");
request.AddParameter("business_unit", "Test");
It is better to create model of c# class and serialize it to Json and send POST request.
Example of RestSharp request
public async Task SendHubSpotRequest()
{
var PortalId = 1;
var formGuid = 1;
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest($"submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
var hubSpotRequest = new HubSpotRequest()
{
SubmittedAt = "1517927174000",
Fields = new Field[]
{
new Field() { Name = "email", Value = "testemail#emailaddress.com" },
new Field() { Name = "firstname", Value = "testfirstname" },
new Field() { Name = "lastname", Value = "testlastname" }
},
Context = new Context
{
Hutk = "hutk",
PageUri = "www.example.com/page",
PageName = "Example page"
},
LegalConsentOptions = new LegalConsentOptions
{
Consent = new Consent
{
// Fill other params
}
}
};
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(hubSpotRequest), ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
var responseContent = response.Content;
}
C# classes of body json model
public class HubSpotRequest
{
[JsonProperty("submittedAt")]
public string SubmittedAt { get; set; }
[JsonProperty("fields")]
public Field[] Fields { get; set; }
[JsonProperty("context")]
public Context Context { get; set; }
[JsonProperty("legalConsentOptions")]
public LegalConsentOptions LegalConsentOptions { get; set; }
}
public class Context
{
[JsonProperty("hutk")]
public string Hutk { get; set; }
[JsonProperty("pageUri")]
public string PageUri { get; set; }
[JsonProperty("pageName")]
public string PageName { get; set; }
}
public class Field
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class LegalConsentOptions
{
[JsonProperty("consent")]
public Consent Consent { get; set; }
}
public class Consent
{
[JsonProperty("consentToProcess")]
public bool ConsentToProcess { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("communications")]
public Communication[] Communications { get; set; }
}
public class Communication
{
[JsonProperty("value")]
public bool Value { get; set; }
[JsonProperty("subscriptionTypeId")]
public long SubscriptionTypeId { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}

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; }
}

When a user selects an item from dropdown list then that item must be removed for that user in mvc 4

I am creating a user course project for learning MVC 4. In this project, when a user logs in they can see their courses and other details. A user can create or edit the courses. So I am displaying list of courses in dropdown list during create and edit. What I want is, when a user selects a course and it is added to his list of courses then that course should not be displayed in the dropdown list for that user. Some code for create is given below:
CourseController:
public ActionResult Create()
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "CourseName");
ViewBag.UserId = usr.UserId;
ViewBag.FirstName = usr.FirstName;
}
return View();
}
//
// POST: /Course/Create
[HttpPost]
public ActionResult Create(UserCourse usercourse)
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
if (ModelState.IsValid)
{
db.UserCourses.Add(usercourse);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "CourseName", usercourse.CourseId);
ViewBag.UserId = usr.UserId;//from c in db.Users.Where(u => u.UserId == usercourse.UserId) select c;
ViewBag.FirstName = usr.FirstName;
return View();
}
return View(usercourse);
}
Create.cshtml:
<div class="editor-label">
#Html.DisplayNameFor(model => model.CourseId)
</div>
<div class="editor-field">
#Html.DropDownList("CourseId", String.Empty)
#Html.ValidationMessageFor(model => model.CourseId)
</div>
<p>
<input type="submit" value="Create" />
</p>
Model class for User:
public partial class User
{
public User()
{
this.UserCourses = new HashSet<UserCourse>();
}
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required(ErrorMessage = "Please Provide User Name", AllowEmptyStrings = false)]
public string UserName { get; set; }
[Required(ErrorMessage = "Please Provide Password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<UserCourse> UserCourses { get; set; }
}
Model class for Course:
public partial class Course
{
public Course()
{
this.UserCourses = new HashSet<UserCourse>();
}
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<UserCourse> UserCourses { get; set; }
}
Model class for UserCourse:
public partial class UserCourse
{
public int Id { get; set; }
public Nullable<int> UserId { get; set; }
public Nullable<int> CourseId { get; set; }
public virtual Course Course { get; set; }
public virtual User User { get; set; }
}
Please reply.
[EDITED]: Try it this way:
public ActionResult Create()
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
var courses = db.Courses.Where(x=>!x.UserCourses.Any(y=>y.CourseId == x.CourseId && y.UserId == usr.UserId)).ToList();
ViewBag.CourseId = new SelectList(courses , "CourseId", "CourseName");
ViewBag.UserId = usr.UserId;
ViewBag.FirstName = usr.FirstName;
}
return View();
}
//
// POST: /Course/Create
[HttpPost]
public ActionResult Create(UserCourse usercourse)
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
if (ModelState.IsValid)
{
db.UserCourses.Add(usercourse);
db.SaveChanges();
return RedirectToAction("Index");
}
var courses = db.Courses.Where(x=>!x.UserCourses.Any(y=>y.CourseId == x.CourseId && y.UserId == usr.UserId)).ToList();
ViewBag.CourseId = new SelectList(courses, "CourseId", "CourseName", usercourse.CourseId);
ViewBag.UserId = usr.UserId;//from c in db.Users.Where(u => u.UserId == usercourse.UserId) select c;
ViewBag.FirstName = usr.FirstName;
return View();
}
return View(usercourse);
}

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");
//}
}

Windows Phone, How to deserialize json which has nested Array

I am now doing a windows phone project, and need to request to a web service for some json data.
if the json structure is like
[Dictionary1,
Dictionary2,
Dictionary3
]
then, DataContractJsonSerializer works fine.
but the next request i will get a complex json data, it doesn't work. like
[
[Dictionary1],
[Dictionary2],
[Dictionary3]
]
real data is:
[
[{"length":5734.042,"duration":1680,"legs":
[
{"length":685,"duration":555.42,"type":"walk","locs":
[
{"coord":{"x":2546445,"y":6675512},"arrTime":"201203290959","depTime":"201203290959","name":null},
{"coord":{"x":2546433.8,"y":6675498.3},"arrTime":"201203291000","depTime":"201203291000","name":"Teekkaripolku"}
]
},
{"length":4158,"duration":420,"type":"5","code":"2506 2","locs":
[
{"coord":{"x":2546168,"y":6674959},"arrTime":"201203291009","depTime":"201203291009","name":"Alvar Aallon puisto","code":"2222235","shortCode":"E2226","stopAddress":"Otaniementie"},
{"coord":{"x":2546337,"y":6674857},"arrTime":"201203291009","depTime":"201203291009","name":"Dipoli","code":"2222204","shortCode":"E2204","stopAddress":"Otaniementie"}
]
}
]
}],
[{"length":5734.042,"duration":1680,"legs":
[
{"length":685,"duration":555.42,"type":"1", "code":"1111", "locs":
[
{"coord":{"x":2546445,"y":6675512},"arrTime":"201203290952","depTime":"201203290952","name":null},
{"coord":{"x":2546433.8,"y":6675498.3},"arrTime":"201203290953","depTime":"201203290953","name":"Teekkaripolku"}
]
},
{"length":4158,"duration":420,"type":"5","code":"2194 2","locs":
[ {"coord":{"x":2546168,"y":6674959},"arrTime":"201203291002","depTime":"201203291002","name":"Alvar Aallon puisto","code":"2222235","shortCode":"E2226","stopAddress":"Otaniementie"},
{"coord":{"x":2546337,"y":6674857},"arrTime":"201203291002","depTime":"201203291002","name":"Dipoli","code":"2222204","shortCode":"E2204","stopAddress":"Otaniementie"}
]
}
]
}]
]
and the class models are :
[DataContract]
public class RouteList
{
[DataMember]
public List<Route> oneRoute;
}
---
[DataContract]
public class Route
{
[DataMember(Name = "length", IsRequired = true)]
public Double length { get; set; }
[DataMember(Name = "duration", IsRequired = true)]
public Double duration { get; set; }
[DataMember(Name = "legs", IsRequired = true)]
public List<Leg> legs { get; set; }
}
----
[DataContract]
public class Leg
{
[DataMember(Name = "length", IsRequired = true)]
public Double length { get; set; }
[DataMember(Name = "duration", IsRequired = true)]
public Double duration { get; set; }
[DataMember(Name = "type", IsRequired = true)]
public String type { get; set; }
[DataMember(Name = "code", IsRequired = false)]
public String code { get; set; }
[DataMember(Name = "locs", IsRequired = true)]
public List<Loc> locs { get; set; }
[DataMember(Name = "shape", IsRequired = false)]
public String shape { get; set; }
}
-----
[DataContract]
public class Loc
{
[DataMember(Name = "coord", IsRequired = true)]
public String coord { get; set; }
[DataMember(Name = "arrTime", IsRequired = true)]
public String arrTime { get; set; }
[DataMember(Name = "depTime", IsRequired = true)]
public String depTime { get; set; }
[DataMember(Name = "name", IsRequired = true)]
public String name { get; set; }
[DataMember(Name = "code", IsRequired = false)]
public String code { get; set; }
[DataMember(Name = "shortCode", IsRequired = false)]
public String shortCode { get; set; }
[DataMember(Name = "stopAddress", IsRequired = false)]
public String stopAddress { get; set; }
}
and the deserializing code:
System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(e.Result));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<RouteList>));
result = (List<RouteList>)serializer.ReadObject(mStream);
i have tried DataContractJsonSerializer and json.NET. but failed. and the most possible problem is the nested arrays, the model:RouteList. anyone knows how to fix it? Thanks a lot.
The issue may be because of your class creation, Before concluding check you model class that handle you parsed result. Or if you want help add more information, like the structure of your model class, the code you used for parsing json etc. Here it seems nothing is complected. Json.Net will do all the tricks, the only effort you need to take is proper building of you class type ..
Enjoy Coding
with the help of Olli Saarikivi, the problem is solved.
with his permission, post his solution here, in case anybody else may need it.
// The request response handler
var routeResults = new List<CompoundRoute>();
if (e.Result.Trim().Length != 0)
{
JArray json = JArray.Parse(e.Result);
foreach (var token in json)
{
var routeArray = token as JArray;
if (routeArray != null)
{
var compoundRoute = new CompoundRoute { Routes = new Route[routeArray.Count] };
for (int i = 0; i < compoundRoute.Routes.Length; ++i)
{
compoundRoute.Routes[i] = new Route(routeArray[i]);
}
routeResults.Add(compoundRoute);
}
}
}
// The data model
[DataContract]
public class CompoundRoute
{
private static readonly Route[] EmptyRoutes = new Route[0];
public CompoundRoute()
{
Routes = EmptyRoutes;
}
[DataMember]
public Route[] Routes;
}
[DataContract]
public class Route
{
public Route(JToken token)
{
Length = token.Value<double>("length");
int durationSeconds = token.Value<int>("duration");
Duration = TimeSpan.FromSeconds(durationSeconds);
JArray legTokens = token["legs"] as JArray;
if (legTokens != null)
{
Legs = new Leg[legTokens.Count];
for (int i = 0; i < Legs.Length; ++i)
{
Legs[i] = new Leg(legTokens[i]);
}
}
}
[DataMember]
public double Length;
[DataMember]
public TimeSpan Duration;
[DataMember]
public Leg[] Legs;
}
[DataContract]
public class Leg
{
public Leg(JToken token)
{
Length = token.Value<double>("length");
double durationSeconds = token.Value<double>("duration");
Duration = TimeSpan.FromSeconds((int)Math.Round(durationSeconds));
Type = token.Value<string>("type");
string lineCode = token.Value<string>("code");
if (lineCode != null)
{
Line = App.Cache.GetOrCreate(lineCode, () => new Line(lineCode));
}
if (Type == "12") // Commuter trains
{
Line.ShortName = Utils.RemoveLeadingNumbers(Line.ShortName);
}
JArray locTokens = token["locs"] as JArray;
if (locTokens != null)
{
Locs = new LegLocation[locTokens.Count];
for (int i = 0; i < Locs.Length; ++i)
{
Locs[i] = new LegLocation(locTokens[i]);
}
}
else
{
Locs = new LegLocation[0];
}
JArray shapeTokens = token["shape"] as JArray;
if (shapeTokens != null)
{
Shape = new ReittiCoordinate[shapeTokens.Count];
for (int i = 0; i < Shape.Length; ++i)
{
var shapeToken = shapeTokens[i];
double x = shapeToken.Value<double>("x");
double y = shapeToken.Value<double>("y");
var coordinate = new ReittiCoordinate(y, x);
Shape[i] = coordinate;
}
}
}
[DataMember]
public double Length;
[DataMember]
public TimeSpan Duration;
[DataMember]
public string Type;
[DataMember]
public Line Line;
[DataMember]
public LegLocation[] Locs;
[DataMember]
public ReittiCoordinate[] Shape;
}
[DataContract]
public class LegLocation
{
public LegLocation(JToken token)
{
var coordToken = token["coord"];
double x = coordToken.Value<double>("x");
double y = coordToken.Value<double>("y");
Coord = new ReittiCoordinate(y, x);
string arrTimeString = token.Value<string>("arrTime");
ArrTime = DateTime.ParseExact(arrTimeString, "yyyyMMddHHmm", null);
string depTimeString = token.Value<string>("depTime");
DepTime = DateTime.ParseExact(depTimeString, "yyyyMMddHHmm", null);
Name = token.Value<string>("name");
}
[DataMember]
public ReittiCoordinate Coord;
[DataMember]
public DateTime ArrTime;
[DataMember]
public DateTime DepTime;
[DataMember]
public string Name;
}