Parsing text into an object in MVC with missing data - c#

I am getting some post data from an HTML form. The data that comes up is used to build a TextualReport object. I want to parse the various pieces of form data that come up and populate those parts of my model.
The reason i am not using a model binder is this is a fairly complex object and indices of my lists can be missing (start at 2, skip 3 etc..). I am starting with an existing object, and only replacing the properties that came up in the post.
I have the following object called TextualReport.
public class TextualReport {
public IList<Section> Sections { get; set; }
public IList<string> MiscInputs { get; set; }
public TextualReport(){
Sections = new List<Section>();
MiscInputs = new List<string>();
}
}
public class Section{
public Section(){
Id = Guid.NewGuid();
Blocks = new List<Block>();
}
public Guid Id { get; set; }
public string Heading { get; set; }
public IList<Block> Blocks { get; set; }
}
public class Block{
public Block(){
PreGraphText = new List<string>();
PreGraphInput = new List<string>();
Graphs = new List<Graph>();
PostGraphText = new List<string>();
}
public Guid Id { get; set; }
public string Heading { get; set; }
public IList<string> PreGraphText { get; set; }
public IList<Graph> Graphs { get; set; }
public IList<string> PostGraphText { get; set; }
public IList<string> PreGraphInput { get; set; }
}
public class Graph{
public string Url { get; set; }
public string Caption { get; set; }
}
From my HTML/Razor form, I get a sequence of text strings like the following:
TextualReport.Sections[1].Blocks[0].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[0].Graphs[1].Caption=
TextualReport.Sections[1].Blocks[0].Graphs[2].Caption=
TextualReport.Sections[1].Blocks[0].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[0].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[1].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[1].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[1].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[2].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[2].Graphs[1].Caption=
TextualReport.Sections[1].Blocks[2].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[2].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[3].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[3].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[3].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[4].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[4].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[4].PreGraphInput[1]=
What would be the best approach to populate my existing data with the various pieces that came up in the form post? I get the model from the database, then update based on the new data.

Related

Serializing Response Inside A Class As A List

I'm trying to fetch Symptoms from an API. I can fetch them already and I'm serializing it inside a class succesfully. The result looks like in image that i share at below:
There are just IDs and Names inside them. The second table from API is like that:
So here my Entity Class;
using System.Collections.Generic;
public class SymptomousInBodySublocations
{
public int ID { get; set; }
public string Name { get; set; }
public bool HasRedFlag { get; set; }
public ICollection<BodyLocations> HealthSymptomLocationIDs { get; set; }
public string ProfName { get; set; }
public List<string> Synonyms { get; set; }
}
And my Serialize Method:
public static List<SymptomousInBodySublocations> SymptomsInBodySublocations()
{
var client = new RestClient("https://priaid-symptom-checker-v1.p.rapidapi.com/symptoms/31/man?format=json&language=en-gb");
var request = new RestRequest(Method.GET);
request.AddHeader("x-rapidapi-host", "priaid-symptom-checker-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "<api-key>");
List<SymptomousInBodySublocations> SymptomsInBodySublocationsList = new List<SymptomousInBodySublocations>();
var response = client.Execute<List<SymptomousInBodySublocations>>(request);
foreach(SymptomousInBodySublocations variables in response.Data)
{
SymptomsInBodySublocationsList.Add(variables);
}
return SymptomsInBodySublocationsList;
}
And my BodyLocations Class:
public class BodyLocations
{
public int ID { get; set; }
public string Name { get; set; }
}
In this point when i tried to fetch my data inside my List<BodyLocations>() the response.Data is empty. What should i do?
HealthSymptomLocationIDs isn't an object, looking at the response it is an array of integers.
Changing the field to match the response should populate the field with the integer values from the API
public List<int> HealthSymptomLocationIDs { get; set; }

Fill dropdown list from database in create view

How can I fetch and insert data at a specific time in one view in mvc razor view? I mean to fill a dropdown list from the database in create view.
I want to fill the following when I add the subject and cheater models.
department list
semester list
standard list
stream list
cheater model:
namespace firstapp.Models
{
public class chepter
{
[ForeignKey("dip_id")]
public int dipart_id { get; set; }
public int chep_id { get; set; }
public string subject { get; set; }
public string chepter { get; set; }
public List<dipartment> dipartlist { get; set; }
public List<dipartment> stdlist { get; set; }
public List<dipartment> semlist { get; set; }
public List<dipartment> stremlist { get; set; }
}
}
department model:
namespace firstapp.Models
{
public class dipartment
{
public int dip_id { get; set; }
public string dipart { get; set; }
public string std { get; set; }
public string sem { get; set; }
public string strem { get; set; }
}
}
#Html.DropDownListFor(model => model.dipart_id, new SelectList(Model.dipartlist.Select(s => new SelectListItem() { Value = s.dip_id, Selected = false, Text = s.dipart })), "Select")
Change your model so the list property is a selectlist:
public SelectList<dipartment> dipartlist { get; set; }
Then, when you populate the model call a service class method(you might not have a service layer, I just prefer to not have database calls in the controller)
dipartlist = _departmentService.GetAsSelectList();
The GetAsSelectList service method looks like this:
public SelectList GetAsSelectList()
{
return (from d in _context.Set<department>().OrderBy(x => x.dipart)
select new
{
Id = d.dipart_id,
Name = d.dipart
}).ToList();
}
And finally your view:
#Html.DropDownListFor(model => model.dipart_id, Model.dipartlist)
This technique means you don't have linq in either the view or controller. Also as you're only creating the selectlist in one place (the service), you can cache it with MemoryCache to prevent multiple requests for the same data. And as it looks like you're populating 4 selectlists, this might be useful.

C# Instance of Lists In Data Model

I've not been able to find an answer so am posting this. If this has already been answered then please point me in that direction.
I have a class model in MVC as below:
public class SearchModel
{
public int id { get; set; }
public string ActivityName { get; set; }
public string Subject { get; set; }
public string Level { get; set; }
public List<LocationModel> Locations { get; set; }
}
public class LocationModel
{
public int LocationID {get; set;}
public string Location { get; set; }
}
I am trying to populate the Locations list in my code but can't seem to get the code to create an instance of it properly.
I have a List of SearchModel as there are multiple items. This is populating fine by doing the following:
List<SearchModel> items = new List<SearchModel>();
and then looping through the following to populate the model.
SearchModel item = new SearchModel();
item.ActivityName = reader["ActivityName"].ToString();
item.Level = reader["LevelNames"].ToString();
item.Subject = reader["SubjectNames"].ToString();
item.id = Convert.ToInt32(reader["ActivityID"]);
items.Add(item);
How do I add the data to the Locations List in the SearchModel? This will contain multiple records also.
item.Locations = new List<LocationModel>();
you can add some data in it
var myLocationModel = new LocationModel();
myLocationModel.Location = "Africa";
item.Locations.Add(myLocationModel);

How should I handle lookups in my ViewModel?

My database table for buildings stores the building type as a code. In a separate lookup table the description for that code is stored.
How should I design my ViewModel and where will I need to make the call to get the associated description value?
I sort of can see one option. I want to know if there is a better option.
BuildingViewModel
{
public string BuildingTypeCode { get;set;}
...other properties
}
Then in my view
code...
<p>#MyService.GetDescription(Model.BuildingTypeCode)</p>
...code
Am I incorrect in the way I am thinking? if I do the above I create a dependency in my View to the service?
Update 1
Working through some of the solutions offered. I seem to run into another issue. I can't access the constructor of each building directly...
public ViewResult Show(string ParcelId)
{
var result = _service.GetProperty(ParcelId);
var AltOwners = _service.GetAltOwners(ParcelId);
var Buildings = _service.GetBuildings(ParcelId);
ParcelDetailViewModel ViewModel = new ParcelDetailViewModel();
ViewModel.AltOwnership = new List<OwnerShipViewModel>();
ViewModel.Buildings = new List<BuildingViewModel>();
AutoMapper.Mapper.Map(result, ViewModel);
AutoMapper.Mapper.Map<IEnumerable<AltOwnership>, IEnumerable<OwnerShipViewModel>>(AltOwners,ViewModel.AltOwnership);
AutoMapper.Mapper.Map<IEnumerable<Building>, IEnumerable<BuildingViewModel>>(Buildings, ViewModel.Buildings);
ViewModel.Pool = _service.HasPool(ParcelId);
ViewModel.Homestead = _service.IsHomestead(ParcelId);
return View(ViewModel);
}
public class ParcelDetailViewModel
{
public IEnumerable<OwnerShipViewModel> AltOwnership { get; set; }
//public IEnumerable<ValueViewModel> Values { get; set; }
public IEnumerable<BuildingViewModel> Buildings { get; set; }
//public IEnumerable<TransferViewModel> Transfers { get; set; }
//public IEnumerable<SiteAddressViewModel> SiteAddresses { get; set; }
public string ParcelID { get; set; }
//public string ParcelDescription { get; set; }
//public int LandArea { get; set; }
//public string Incorporation { get; set; }
//public string SubdivisionCode {get;set;}
public string UseCode { get; set; }
//public string SecTwpRge { get; set; }
//public string Census { get; set; }
//public string Zoning { get; set; }
public Boolean Homestead {get;set;}
//public int TotalBuildingArea { get; set; }
//public int TotalLivingArea { get; set; }
//public int LivingUnits { get; set; }
//public int Beds { get; set; }
//public decimal Baths { get; set; }
public short Pool { get; set; }
//public int YearBuilt { get; set; }
}
My understanding is that the view model is meant for display ready data. I think the real problem here is putting model dependent logic into the view.
You can do your service lookup but keep that code in the controller. The view model should be considered display ready (save for some formatting).
class BuildingViewModel
{
public string BuildingTypeCode { get;set;}
...other properties
}
and then do the lookup before you render:
public ActionResult Building()
{
var typeCode = // get from original source?
var model = new BuildingViewModel
{
BuildingTypeCode = MyService.GetDescription(typeCode)
};
return View("Building", model);
}
Having come from a long line of JSP custom tags I dread having any code hidden in the view layout. IMO, that layer should be as dumb as possible.
I would recommend having a helper that does that, or a DisplayTemplate
public class ViewHelpers
{
public static string GetDescription(string code)
{
MyService.GetDescription(Model.BuildingTypeCode);
}
}
or
#ModelType string
#Html.DisplayFor("",MyService.GetDescription(Model.BuildingTypeCode));
More info on templates: http://www.headcrash.us/blog/2011/09/custom-display-and-editor-templates-with-asp-net-mvc-3-razor/
Both of these approaches introduce a dependency on your service but you can test/change them in one single place, instead of the whole application (plus the usage looks cleaner).

Storing and retrieving from lists with custom structures in

I'm having some trouble storing and retrieving items into a list<> with a custom structure.
My structure looks like this:
public class list_rss_parameters
{
public string this_string { get; set; }
public string title_start { get; set; }
public string title_end { get; set; }
public string description_start { get; set; }
public string description_end { get; set; }
public string link_start { get; set; }
public string link_end { get; set; }
public string publish_date_start { get; set; }
public string publish_date_end { get; set; }
public string author_start { get; set; }
public string author_end { get; set; }
}
My stored procedure looks like this (and note that the variable names are the same as the custom Key names) Is this ok?
//this is the last part of a custom method that returns a list
List<list_rss_parameters> list_rss_items = new List<list_rss_parameters>();
list_rss_items.Add(new list_rss_parameters()
{
this_string = this_string,
title_start = title_start,
title_end = title_end,
description_start = description_start,
description_end = description_end,
link_start = link_start,
link_end = link_end,
publish_date_start = publish_date_start,
publish_date_end = publish_date_end,
author_start = author_start,
author_end = author_end
});
return list_rss_items;
If the above two setups are correct, how do I pull items out of the List once I return it?
List<list_rss_parameters> list_rss_parameters = new List<list_rss_parameters>();
list_rss_parameters = f_discover_rss_parameters(rss);
show(list_rss_parameters.Count.ToString());
show(list_rss_parameters[0].ToString()); //does not show this_string
show(list_rss_parameters[this_string'] //does not show this_string
show(list_rss_parameters[0][this_string'];//does not show this_string
What am I doing wrong?
You want the this_string property of the first item in your list it seems:
show(list_rss_parameters[0].this_string);
Or show all of them:
foreach(var item in list_rss_parameters)
{
Console.WriteLine(item.this_string);
}
As a side note your property names don't match the PascalCase naming convention for properties in .NET - so this_string really should be ThisString.

Categories