Set DeserializeObject in anonymous property of a class - c#

I have this:
public class ComponentData
{
public dynamic CdHtml { get; set; }
public dynamic CdJson { get; set; }
public dynamic CdSection { get; set; }
public dynamic CdContainer { get; set; }
public dynamic CdRow { get; set; }
public dynamic CdContainerId { get; set; }
public dynamic CdColsJson { get; set; }
}
And i want to set the ComponentData Class with these values but i get an error:
var componentData = new ComponentData()
{
CdHtml = obj.htmlCD,
CdJson = JsonConvert.DeserializeObject<dynamic>(obj.jsonCD),
CdContainerId = "SECTION" + obj.CD_Container_Id,
CdSection = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson("xxx" + obj.CD_Container_Id, "width:" + tlj.width.ToString() + "%;padding-left:30px;padding-right:30px;padding-top:30px;padding-bottom:30px;" + sectionCenterStyle, "section")),
CdContainer = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson("xxx" + obj.divGUID2, containerStyle, "container")),
CdRow = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson("xxx" + obj.divGUID3, "", "row")),
CdColsJson = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson(obj.divGUID4, "", string.Format("col-xs-{0} col-sm-{1} col-md-{2} col-lg-{3} hoversel colregion{4}", bsc.xs, bsc.sm, bsc.md, bsc.lg, obj.divGUID4), bsc.xs, bsc.sm, bsc.md, bsc.lg))
};
return Json(new { componentData = componentData, html = obj.html });
how would i return this class with the json objects inside and pass it back to the client using ajax?

Change your code to this:
var componentData = new ComponentData()
{
CdHtml = obj.htmlCD,
CdJson = JsonConvert.DeserializeObject<ExpandoObject>(obj.jsonCD),
CdContainerId = "SECTION" + obj.CD_Container_Id,
CdSection = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson("xxx" + obj.CD_Container_Id, "width:" + tlj.width.ToString() + "%;padding-left:30px;padding-right:30px;padding-top:30px;padding-bottom:30px;" + sectionCenterStyle, "section")),
CdContainer = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson("xxx" + obj.divGUID2, containerStyle, "container")),
CdRow = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson("xxx" + obj.divGUID3, "", "row")),
CdColsJson = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson(obj.divGUID4, "", string.Format("col-xs-{0} col-sm-{1} col-md-{2} col-lg-{3} hoversel colregion{4}", bsc.xs, bsc.sm, bsc.md, bsc.lg, obj.divGUID4), bsc.xs, bsc.sm, bsc.md, bsc.lg))
};
If you want to convert to dynamic you need to use ExpandoObject just as you would use when you want to create one with your hands.

Related

One to many mapping on query dapper

I'm trying to query one to many on dapper but for some reason I only get 1 value back from my joined table even though I should be getting multiple as from my query
Can someone tell me what I did wrong?
I tried doing what was mentioned in the following post answer Mapping one to many with Dapper
My code:
public class MonsterDatabase
{
public int Id { get; set; }
public int MonsterId { get; set; }
public string Name { get; set; }
public List<MonsterLocationDatabase> Location { get; set; }
}
public class MonsterLocationDatabase
{
public int Id { get; set; }
public int FkMonsterId { get; set; }
public string Map { get; set; }
public int Frequency { get; set; }
public string MapImage { get; set; }
public DateTime? DeathTime { get; set; }
public DateTime? RespawnTime { get; set; }
}
public static MonsterDatabase GetMonster(Monster monster)
{
using (var connection = new SqlConnection(config["appsettings:RagnaDatabase"]))
{
var Monster = connection.Query<MonsterDatabase, MonsterLocationDatabase, MonsterDatabase>(
"select top 1 Monster.*, SplitMonster = '', MonsterLocation.*" +
" from Monster" +
" join MonsterLocation" +
" on Monster.Id = MonsterLocation.FkMonsterId",
(Monster, Location) =>
{
Monster.Location = new List<MonsterLocationDatabase>();
Monster.Location.Add(Location);
return Monster;
}, splitOn: "SplitMonster"
).FirstOrDefault();
return Monster;
}
}
I was able to fix the issue by following the one to many dapper documentation on
https://dapper-tutorial.net/result-multi-mapping
public static MonsterDatabase GetMonster()
{
using (var connection = new SqlConnection(config["appsettings:RagnaDatabase"]))
{
var monsterDictionary = new Dictionary<int, MonsterDatabase>();
var Monster = connection.Query<MonsterDatabase, MonsterLocationDatabase, MonsterDatabase>(
"select top 10 Monster.*, SplitMonster = '', MonsterLocation.*" +
" from Monster" +
" left join MonsterLocation" +
" on Monster.Id = MonsterLocation.FkMonsterId",
(Monster, Location) =>
{
MonsterDatabase monsterEntry;
if(!monsterDictionary.TryGetValue(Monster.Id, out monsterEntry))
{
monsterEntry = Monster;
monsterEntry.Location = new List<MonsterLocationDatabase>();
monsterDictionary.Add(monsterEntry.Id, monsterEntry);
}
monsterEntry.Location.Add(Location);
return monsterEntry;
}, splitOn: "SplitMonster"
).Distinct().FirstOrDefault();
return Monster;
}
}

adding multiple values in object list in web api c#

I am new to web api and C#. I am creating a function where I am calling values from table which has 33 rows. the query is this:
Select * from T_SVRS_Reg_Trans
I have created a model where I have put out properties like so:
public class UserModel
{
public int ID { get; set; }
public string OrgUnit { get; set; }
public string TDC { get; set; }
public string CustCode { get; set; }
public string CustName { get; set; }
public string DestCode { get; set; }
public string EMV { get; set; }
public string Service { get; set; }
public string SPCCode { get; set; }
public string SPCode { get; set; }
public string Remarks { get; set; }
public int Stage { get; set; }
public string Cost { get; set; }
public string SAPUpdate { get; set; }
public string Active { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedOn { get; set; }
}
Now I am calling the table values to get added in these properties. My function for that is this:
[HttpPost]
[Route("GetTableValue")]
public IHttpActionResult GetTableValue()
{
try
{
UserModel objUserModel = new UserModel();
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
objUserModel.OrgUnit=(sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
}
}
return Ok(objUserModel);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
However I am noticing that only the last table value is added to the model and the rest of it is not. I want to add all 33 values in model form to the model mentioned. Is there any way to do this?
PLease help
}
You overwrite objUserModel each iteration. Create a new one inside the loop, add them to a List<UserModel>, returning that to your view.
Also consider dropping the archaic Hungarian notation (the "obj" prefix). Also consider using an ORM instead of mapping columns to properties using strings.
You should create a List or Array of type UserModel and adding items into it
try
{
List<UserModel> result = new List<UserModel>();
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
UserModel objUserModel = new UserModel();
objUserModel.OrgUnit = (sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
result.Add(objUserModel);
}
}
return Ok(result);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
You need to use the collection instead of single object UserModel.
[HttpPost]
[Route("GetTableValue")]
public IHttpActionResult GetTableValue()
{
try
{
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
List<UserModel> userModels = new List<UserModel>();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
var objUserModel = new UserModel()
objUserModel.OrgUnit = (sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
userModels.Add(userModels);
}
}
return Ok(userModels);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
}
As you are expecting more than one row to be returned, you need to collect the rows as you iterate your result set into some sort of collection/list/array.
Try making a list of your UserModel
List<UserModel> objUserModels = new List<UserModel>();
And then adding each object to the list after each iteration of your for loop:
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
var objUserModel = new UserModel();
objUserModel.OrgUnit=(sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
objUserModels.Add(objUserModel);
}
And then return your list of objects:
return Ok(objUserModels);

Map one class data to another class with iteration

I have a C# project and looking for simple solution for map one class object data to list of another class object.
This is my input class
public class RatesInput
{
public string Type1 { get; set; }
public string Break1 { get; set; }
public string Basic1 { get; set; }
public string Rate1 { get; set; }
public string Type2 { get; set; }
public string Break2 { get; set; }
public string Basic2 { get; set; }
public string Rate2 { get; set; }
public string Type3 { get; set; }
public string Break3 { get; set; }
public string Basic3 { get; set; }
public string Rate3 { get; set; }
}
This is my another class structure
public class RateDetail
{
public string RateType { get; set; }
public decimal Break { get; set; }
public decimal Basic { get; set; }
public decimal Rate { get; set; }
}
it has a object like below. (For easiering the understanding, I use hardcoded values and actually values assign from a csv file)
RatesInput objInput = new RatesInput();
objInput.Type1 = "T";
objInput.Break1 = 100;
objInput.Basic1 = 50;
objInput.Rate1 = 0.08;
objInput.Type2 = "T";
objInput.Break2 = 200;
objInput.Basic2 = 50;
objInput.Rate2 = 0.07;
objInput.Type3 = "T";
objInput.Break3 = 500;
objInput.Basic3 = 50;
objInput.Rate3 = 0.06;
Then I need to assign values to "RateDetail" list object like below.
List<RateDetail> lstDetails = new List<RateDetail>();
//START Looping using foreach or any looping mechanism
RateDetail obj = new RateDetail();
obj.RateType = //first iteration this should be assigned objInput.Type1, 2nd iteration objInput.Type2 etc....
obj.Break = //first iteration this should be assigned objInput.Break1 , 2nd iteration objInput.Break2 etc....
obj.Basic = //first iteration this should be assigned objInput.Basic1 , 2nd iteration objInput.Basic2 etc....
obj.Rate = //first iteration this should be assigned objInput.Rate1, 2nd iteration objInput.Rate2 etc....
lstDetails.Add(obj); //Add obj to the list
//END looping
Is there any way to convert "RatesInput" class data to "RateDetail" class like above method in C#? If yes, how to iterate data set?
Try this:
public class RatesList : IEnumerable<RateDetail>
{
public RatesList(IEnumerable<RatesInput> ratesInputList)
{
RatesInputList = ratesInputList;
}
private readonly IEnumerable<RatesInput> RatesInputList;
public IEnumerator<RateDetail> GetEnumerator()
{
foreach (var ratesInput in RatesInputList)
{
yield return new RateDetail
{
RateType = ratesInput.Type1,
Break = Convert.ToDecimal(ratesInput.Break1, new CultureInfo("en-US")),
Basic = Convert.ToDecimal(ratesInput.Basic1, new CultureInfo("en-US")),
Rate = Convert.ToDecimal(ratesInput.Rate1, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type2,
Break = Convert.ToDecimal(ratesInput.Break2),
Basic = Convert.ToDecimal(ratesInput.Basic2),
Rate = Convert.ToDecimal(ratesInput.Rate2, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type3,
Break = Convert.ToDecimal(ratesInput.Break3),
Basic = Convert.ToDecimal(ratesInput.Basic3),
Rate = Convert.ToDecimal(ratesInput.Rate3, new CultureInfo("en-US"))
};
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
And use:
var list = new RatesList(new List<RatesInput>() { objInput });
foreach (var item in list)
{
Console.WriteLine(item.Basic);
}
You can use Reflection to get the properties info like this:
var props = objInput.GetType().GetProperties();
var types = props.Where(x => x.Name.StartsWith("Type"))
.Select(x => x.GetValue(objInput)).ToList();
var breaks = props.Where(x => x.Name.StartsWith("Break"))
.Select(x => x.GetValue(objInput)).ToList();
var basics = props.Where(x => x.Name.StartsWith("Basic"))
.Select(x => x.GetValue(objInput)).ToList();
var rates = props.Where(x => x.Name.StartsWith("Rate"))
.Select(x => x.GetValue(objInput)).ToList();
List<RateDetail> lstDetails = new List<RateDetail>();
for (int i = 0; i < types.Count; i++)
{
lstDetails.Add(new RateDetail
{
RateType = types[i].ToString(),
Break = Convert.ToDecimal(breaks[i]),
Basic = Convert.ToDecimal(basics[i]),
Rate = Convert.ToDecimal(rates[i])
});
}

Accessing value by key in property dictionary

Im trying to access and display the value of a dictionary where the dictionary has no real name but is a property of a class.
Currently I have an enum "Roles" with three elements (fighter, rogue, and sorcerer), and:
public class Adventurer
{
public int ID { get; set; }
public string Name { get; set; }
public Roles Role { get; set; }
public List<Skill> Skills { get; set; }
public override string ToString()
{
return $"{ID}" + " - " + $"{Name}" + " - " + $"{Role}";
}
}
and:
public class Skill
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Dictionary<Roles, Skill> LinkedTo { get; set; }
}
and in another class I have:
private void CreateSkills()
{
Skill swordFighting = new Skill() { ID = 1, Name = "Sword fighting"};
Skill stealth = new Skill() { ID = 2, Name = "Stealth"};
Skill magic = new Skill() { ID = 3, Name = "Magic"};
swordFighting.LinkedTo = new Dictionary<Roles, Skill>
{
{ Roles.Fighter, swordFighting }
};
stealth.LinkedTo = new Dictionary<Roles, Skill>
{
{ Roles.Rogue, stealth }
};
magic.LinkedTo = new Dictionary<Roles, Skill>
{
{ Roles.Sorcerer, magic }
};
}
private void DisplaySkills(Adventurer adventurer)
{
adventurer.Skills = adventurer.Role.LinkedTo; // I WOULD LIKE SOMETHING LIKE THIS...
lstAdventurer.ItemsSource = adventurer.Skills;
}
Is there some way of accessing the values (skills) of the adventurer by knowing only the role (fighter/rogue/sorcerer)?
Best,
Dedoj
Would you mean something like this?
for known Roles like Roles.Fighter:
adventurer.Skills = adventurer.Skills
.Select(s => s.LinkedTo.ContainsKey(Roles.Fighter) ? s.LinkedTo[Roles.Fighter] : null)
.Where(s => s != null).ToList();

Cannot pass KeyValuePair to controller, values null

im trying pass a object since View to controller as ViewModel. But some arrive field empty to controller. This fields are KeyValuePair and have not idea for pass it correctly to Controller.
This is my code:
Controller:
public ActionResult Index(SearchResultsViewModel searchResultsViewModel)
{
PassengerDataViewModel viewModel = new PassengerDataViewModel()
{
Request = searchResultsViewModel,
PassengerType = GetPassengerTypes(),
NumberPeople = GetNumberPeople()
};
return View("PassengerData", viewModel);
}
ViewModel:
public class SearchResultsViewModel
{
public SearchViewModel Request { get; set; }
public string SearchFlightDatesText { get; set; }
public string SearchPaxSelectionText { get; set; }
public KeyValuePair<string, string> DepartureStation { get; set; }
public KeyValuePair<string, string> ArrivalStation { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
public DateTime SelectedDate { get; set; }
public int SelectedDay { get; set; }
public List<FlightsResponseDTO> Days { get; set; }
public KeyValuePair<string, string> DepartureStation2 { get; set; }
public KeyValuePair<string, string> ArrivalStation2 { get; set; }
public List<FlightsResponseDTO> Days2 { get; set; }
public DateTime BeginDate2 { get; set; }
public DateTime EndDate2 { get; set; }
public DateTime SelectedDate2 { get; set; }
public int SelectedDay2 { get; set; }
}
View Code
Post = function (path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
debugger;
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
debugger;
document.body.appendChild(form);
form.submit();
}
$("a.baseButton.yellowButton.mediumButton").click(function (event) {
//Comprobamos si esta seleccionado un vuelo
if(!checkIfFlightSelected()){
$('#error-dialog').dialog({
modal: true,
height: 130,
width: 360
});
event.preventDefault();
return false;
}
//--------------Inicio SearchViewModel ------------------------------
debugger;
var departureStation = "#Model.Request.SelectedOrigin1";
var arrivalStation = "#Model.Request.SelectedDestination1";
var departureDate = "#Model.Request.SelectedFlightDate1";
var departureStation2 = "#Model.Request.SelectedOrigin2";
var arrivalStation2 = "#Model.Request.SelectedDestination2";
var departureDate2 = "#Model.Request.SelectedFlightDate2";
var adults = "#Model.Request.NumAdults";
var childs = "#Model.Request.NumChilds";
var infants = "#Model.Request.NumInfants";
var residentOrFamily ="#Model.Request.SelectedResidentOrLargueFamilyDiscount";
var PassengersWithDiscount = "#Model.Request.NumPassengersWithSpecialDiscount";
var tipo = "#Model.Request.SelectedSearchType";
var searchViewModelRequest = {
SelectedSearchType: tipo,
SelectedOrigin1: departureStation,
SelectedDestination1: arrivalStation,
SelectedFlightDate1: departureDate,
Tipo:tipo,
//SelectedOrigin2: departureStation2,
//SelectedDestination2: arrivalStation2,
//SelectedFlightDate2: departureDate2,
NumAdults: adults,
NumChilds: childs,
NumInfants: infants,
SelectedResidentOrLargueFamilyDiscount: residentOrFamily,
NumPassengersWithSpecialDiscount: PassengersWithDiscount
};
//-------------------Fin SearchViewModel---------------------------------
//Inicio SearchResultsViewModel
//-----------Datos para obtenr datos seleccioandos------------------
var partsId = $("#availabilityTable0 :input:checked")[0].id.split('_');
var day = calendariCarregat.Days[partsId[1]];
var journey=day.Journeys[partsId[2]];
var departureDate = new Date(journey.JourneySellKey.split('~')[5].split(' ')[0]);
//var arrivalDate = new Date(journey.JourneySellKey.split('~')[7].split(' ')[0]);
var departureHourDate = journey.DepartureTimeString;
var arrivalHourDate = journey.ArrivalTimeString;
var departureDay;
var departureMonth;
if (departureDate.getUTCDate() + 1 < 10) {
departureDay = "0" + (departureDate.getUTCDate() + 1);
} else {
departureDay = (departureDate.getUTCDate() + 1);
}
if (departureDate.getUTCDate() + 1 < 10) {
departureMonth = "0" + (departureDate.getUTCMonth() + 1);
} else {
departureMonth = (departureDate.getUTCMonth() + 1);
}
var normalDepartureDate = (departureDay) + "/" + (departureMonth) + "/" + departureDate.getUTCFullYear();
//----------------------Fin datos seleccionados--------------
var searchFlightDatesText = "#Model.SearchFlightDatesText";
var searchPaxSelectionText = "#Model.SearchPaxSelectionText";
var departureStation = {
"Key": "#Model.DepartureStation.Key",
"Value": "#Model.DepartureStation.Value"
};
var arrivalStation = {
"Key": "#Model.ArrivalStation.Key",
"Value": "#Model.ArrivalStation.Value"
};
var beginDate = "#Model.BeginDate";
var endDate = "#Model.EndDate";
var selectedDate = normalDepartureDate;
var selectedDay = "#Model.SelectedDay";
var days = "#Model.Days";
//var departureStation2 = null;
//var arrivalStation2 = null;
//var days2 = null;
//var beginDate2 = null;
//var endDate2 = null;
//var selectedDate2 = null;
//var selectedDay2 = null;
var searchResultsViewModel = {
//Request: searchViewModelRequest.toString(),
"Request.SelectedOrigin1": searchViewModelRequest.SelectedOrigin1,
"Request.SelectedSearchType": searchViewModelRequest.Tipo,
"Request.SelectedDestination1": searchViewModelRequest.SelectedDestination1,
"Request.SelectedFlightDate1": searchViewModelRequest.SelectedFlightDate1,
"Request.NumAdults": searchViewModelRequest.NumAdults,
"Request.NumChilds": searchViewModelRequest.NumChilds,
"Request.NumInfants": searchViewModelRequest.NumInfants,
"Request.IncrementSelectedFlightDate1": 0,
"Request.SelectedResidentOrLargueFamilyDiscount": searchViewModelRequest.SelectedResidentOrLargueFamilyDiscount,
"Request.NumPassengersWithSpecialDiscount": searchViewModelRequest.NumPassengersWithSpecialDiscount,
SearchFlightDatesText: searchFlightDatesText,
SearchPaxSelectionText: searchPaxSelectionText,
"DepartureStation.Key": "test",
"DepartureStation.Value": "test",
"ArrivalStation": "{ [test, test]}",
BeginDate: beginDate,
EndDate: endDate,
SelectedDate: selectedDate,
SelectedDay: selectedDay,
Days: days,
"DepartureStation2.Key": "test",
"DepartureStation2.Value": "test",
};
//--------------Fin SearchResultsViewModel
MICESearcher.Post('#Url.Action("Index", "PassengerData")', (searchResultsViewModel));
});
i have tried it pass values of many ways to the KeyValuePair but i could not achieve it
Edit(solved):
finally thanks to #Daniel J.G, I could solve the problem by following this website ASP MVC.NET - how to bind KeyValuePair?
thank you all for the help!!

Categories

Resources