How to select object in dropdown - javascript

I have a City class
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
}
and Ride class.
public class Ride
{
public Guid Id { get; set; }
public City From { get; set; }
public List<City> To { get; set; }
public DateTime DateAndTime { get; set; }
}
What is the best way to load cities, pass it to view, show them in dropdownlists and POST data back to controller? Best would be if I could add more than one City to To column.
I have found Selectize.js but I have no experience with JavaScript. Can I pass to options only JSON etc or could it be a list of cities from database.
Thank you for your time.

You'll need a view model, especially if you want to select multiple cities at once. For example:
public class RideViewModel
{
public Guid Id { get; set; }
public DateTime DateAndTime { get; set; }
public int FromCityId { get; set; }
public List<int> ToCityIds { get; set; }
public IEnumerable<SelectListItem> CityChoices { get; set; }
}
Notice that there's no List<City> property on the view model. Instead, there's ToCityIds which will store the selected id values from the list box and CityChoices which will be used to populate the list box. You can't post full City objects from a list box, only simple types like int. So, on POST you'll use the values from ToCityIds to lookup up the City instances from the database. The same goes for your From property on your entity.
Now, in your controller:
private void PopulateCityChoices(RideViewModel model)
{
model.CityChoices = db.Cities.Select(m => new SelectListItem
{
Value = m.Id,
Text = m.Name
});
}
public ActionResult Create()
{
var model = new RideViewModel();
PopulateCityChoices(model);
return View(model);
}
[HttpPost]
public ActionResult Create(RideViewModel model)
{
if (ModelState.IsValid)
{
// Create new `Ride` and map data over from model
var ride = new Ride
{
Id = Guid.NewGuid(),
DateAndTime = model.DateAndTime,
From = db.Cities.Find(model.FromCityId),
To = db.Cities.Where(m => m.ToCityIds.Contains(m.Id))
}
db.Rides.Add(ride);
db.SaveChanges();
}
// Must repopulate `CityChoices` after post if you need to return the form
// view again due to an error.
PopulateCityChoices(model);
return View(model);
}
Finally in your view change the model declaration to:
#model Namespace.To.RideViewModel
And then add your From select list and To list box:
#Html.DropDownListFor(m => m.FromCityId, Model.CityChoices)
#Html.ListBoxFor(m => m.ToCityIds, Model.CityChoices)
You can use the same choices for both, since they're both selecting cities.

Related

How do I construct this json string and take its values in the action method? (scenario provided)

image
In the image link above I have created a form which can dynamically add more rows of input fields
The values from the input field that are dynamically added are pushed into an array while the values on the green part are place into a javascript object.
reservations.push({ Day:d, Room: r, TimeIn: datetimeIn.toString(), TimeOut: datetimeOut.toString()});//this is assuming that only 1 row of input field was added
var r = JSON.stringify(reservations);
//There's only 1 course, description, section, datefrom and dateto while there can be many Day, Room, TimeIn, TimeOut.
var reservation = { CourseCode: courseCode.val(), Description: description.val(), Section: section.val(), DateFrom: dateF, DateTo: dateT, r };
$.ajax({
url: '/ReserveSubject',
type: 'POST',
data: 'reservation=' + JSON.stringify(reservation),
How do I take the values of the json string and create and instance of an object that will take those values
[HttpPost]
public ActionResult ReserveSubject(string reservation)
{
Subject sub = new Subject();
sub.CourseCode = reservation.CourseCode;
sub.Description = reservationDescription;
.
.
.
//loop through reservation data from dynamically added rows of input field
{
Schedule sch = new Schedule();
sch.Day = reservation.Day;
sch.Room = reservation.Room;
.
.
.
sub.Schedule.add(sch);
}
sub.ScheduleTable = MethodThatWillConvertScheduleListToDatatable(sub.Schedule);
}
Object to instantiate
public class Subject
{
string CourseCode { get; set; }
string Description { get; set; }
string Section { get; set; }
string DateFrom { get; set; }
string DateTo { get; set; }
List<Schedule> Schedule { get; set; }
DataTable ScheduleTable { get; set; }
}
public class Schedule
{
string Day { get; set; }
string Room { get; set; }
string TimeIn { get; set; }
string Timeout { get; set; }
}
I have already downloaded NewtonSoft as i think most of your answer will make use of it.
var jsonObject = {
"Prop1" : "something",
"Prop2" : "something",
"Prop3List" : GetSomeJsonScheduleList()
etc...
};
public class ExampleModel
{
public string Prop1 {get; set;}
public string Prop2 {get; set;}
public IList<Schedule> Prop3List {get; set;}
}
public ActionResult ControllerMethod(ExampleModel model)
{
//Use your model like normal
}
Then just JSON.stringify(jsonObject) in your ajax call.
Take note of the naming conventions.

Converting MVC Model List to JSLINQ Error

I have three dropdownlist BodyPart, ExamDetail and ExamView and I have complete data set for these lists. I don't need to call controller again and again whenever the dropdown change event call but I want to fetch list from my model's property list. I am using JS Library to apply LINQ Queryto avoid any loops in code.
My Class Architecture is given below:
public class BodyPart
{
public string ID { get; set; }
public string Text { get; set; }
public List<ExamDetail> examdetail { get; set; }
}
public class ExamDetail
{
public string ID { get; set; }
public string Text { get; set; }
public List<ExamView> examview { get; set; }
}
public class ExamView
{
public string ID { get; set; }
public string Text { get; set; }
}
I have proper data in all my list, here is my js code to fetch ExamDetail Record
var selectedBodyPart = $("#BodyPartDDL").val();
var examdetailList = JSLINQ(#Model.bodypart).Where(function (item) {
return item.ID == selectedBodyPart; });
But I am getting "Uncaught SyntaxError: Unterminated template literal(…)" error where I pass my model list. I need to pass this examdetailList to my ExamDetail partial view. Thank you.

Hidden form submit with model as parameter

I'm trying to figure out how to send the MVC Model to my ActionResult method, but the data on the AccountsManagementDetailsModel model is always empty or null, even though the model object itself is properly constructed, only with empty properties.
My method on the controller:
public async Task<ActionResult> ResetPassword(AccountsManagementDetailsModel model)
{
...
}
My JQuery:
var form = $('<form action="#Url.Action("ResetPassword", "AccountsManagement")" method="POST">');
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "model").val(#Html.Raw(Json.Encode(Model)));
form.append(input + "</input></form>");
form.appendTo('body').submit();
My AccountsManagementDetailsModel:
public class AccountsManagementDetailsModel : UserInfo
{
public bool New { get; set; }
}
public class UserInfo
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
public bool Customer { get; set; }
public string CustomerID { get; set; }
public bool MustChangePassword { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm}", ApplyFormatInEditMode = true)]
public DateTime? LastLogin { get; set; }
}
What am I doing wrong?
The right way to sent your model is create inputs for each property of your model. It could be difficult but you can use EditorTemplate that generate you html with assistance of HtmlHelpers.
The easiest way that i can see is to change your code like this:
var form = $('<form action="#Url.Action("ResetPassword", "AccountsManagement")" method="POST">' + formHtml + "</form>");
var formHtml = '#Html.Raw(Html.EditorForModel().ToString().Replace("\r\n", "<br />"))';
form.append(formHtml + "</form>");
form.appendTo('body').submit();
Helper EditorForModel should create valid inputs (with right name attributes) for you and allow you to post model to controller and bind it there.
Anyway if you don't want to change your code this way you can change your controller code like this:
public async Task<ActionResult> ResetPassword(string model)
{
AccountsManagementDetailsModel modelBind = new JavaScriptSerializer().Deserialize<AccountsManagementDetailsModel>(model);
}
This lines should deserialize your serialized string from Json to your model.

How to represent the value reference to my lookup data in my ViewModel?

I have a list of (for example) countries in my database, which might have a class representation that looks like;
public class Country {
public int CountryId { get; set; }
public string CountryName { get; set; }
}
Now i have a ViewModel class that models a Student for example, and it looks like;
public class StudentViewModel {
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
When i want to provide the Country the Student comes from, i usually include the following properties in the StudentViewModel class;
public int CountryId { get; set; }
public string CountryName { get; set; }
Now, i not quite sure if i am doing the right thing because on the client (using javascript), i have to keep the CountryId and CountryName synchronized. The reason i have done it this way for a while is because i used the CountryId property to set the initial value of the dropdownlist and CountryName to show the textual value on a different section of the same form.
I would like to know how other people are handling situations like this?

bind JSON list in array to ASP.NET model class

I am building JSON output from my array that I am intended to pass back to server where I have model class to bind JSON data variable to class variables. In this class I am also taking multiple records of say for argument 'Component' and to bind this part I have IList in my model class.
Now I have managed to pass data back to controller except the Components that is in IList... I am struggling to find answer.. your help will be really appreciated..
Model class
public class QualificationElementComponents_ViewModel
{
public int ElementIndex { get; set; }
public string ElementMarkingSchemeTitle { get; set; }
public int ElementAvailableMark { get; set; }
public int ElementPassMark { get; set; }
public int ElementMeritMark { get; set; }
public int ElementDistinctionMark { get; set; }
public IList<ECom1> ElementComponent { get; set; }
}
IList 'Component' Model class
public class ECom1
{
public int componentIndex { get; set; }
public int componentMark { get; set; }
}
Controller Method
public ActionResult CreateNewQualification(QualificationViewModel newQualificationData, IList<QualificationElementComponents_ViewModel> ElementComponentList)
{
in view
//build component list... possible will have multiple records in array
selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });
// build element list
selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark });
//bind arrays
selectElementList.push({ ElementComponent: selectedComponentList });
QualificationElemenetsAndComponentsList.push.apply(QualificationElemenetsAndComponentsList, selectElementList);
JSON Output
{"QualificationElemenetsAndComponentsList":[{"ElementIndex":1,"ElementMarkingSchemeTitle":"fg","ElementAvailableMark":"56","ElementPassMark":"6","ElementMeritMark":"5","ElementDistinctionMark":"6"},{"ElementComponent":[{"componentIndex":1,"componentMark":"23"},{"componentIndex":2,"componentMark":"44"}]}]}
require JSON Output
in comparison to above JSON I require following JSON format
{"QualificationElemenetsAndComponentsList":[{"ElementIndex":1,"ElementMarkingSchemeTitle":"d2","ElementAvailableMark":"223","ElementPassMark":"32","ElementMeritMark":"12","ElementDistinctionMark":"2","ElementComponent":[{"componentIndex":2,"componentMark":551}]}]}
Instead of adding the ElementComponent property to a new object and then into the array, you need to include it with the other properties like so:
//build component list... possible will have multiple records in array
selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });
// build element list
selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark, ElementComponent: selectedComponentList });
//Add ElementComponent with all the other properties

Categories

Resources