How to show one value and post another one in .net core? [duplicate] - mysql

I have 2 classes. Photos and Albums
I need to include the Album names in my Photos/Create View and create Dropdowns for Album names.
The model in my View Photo/Create is : ImageViewModel
How can I get it?
public class Album
{
public int Id { get; set; }
[Required]
[MinLength(5), MaxLength(100)]
public string Name { get; set; }
private DateTime? dateCreated = null;
public DateTime CreatedOn
{
get => dateCreated.HasValue ? this.dateCreated.Value : DateTime.Now;
set => this.dateCreated = value;
}
public virtual List<PhotoAlbums> PhotoAlbums { get; set; }
}
public class PhotoAlbums
{
public int PhotoId { get; set; }
public Photo Photo { get; set; }
public int AlbumId { get; set; }
public Album Album { get; set; }
}
public class Photo
{
public int Id { get; set; }
public byte[] Picture { get; set; }
public string Name { get; set; }
public string AlbumNames { get; set; }
public virtual List<PhotoAlbums> PhotoAlbums { get; set; }
}
public class ImageViewModel
{
private readonly IUnitOfWork _unitOfWork;
public ImageViewModel()
{
_unitOfWork = new UnitOfWork<ApplicationDbContext>();
}
public int Id { get; set; }
public string FileName { get; set; }
public byte[] ImageData { get; set; }
public string File { get; set; }
public string Albumname { get; set; }
public string ImageSrc
{
get
{
string base64 = Convert.ToBase64String(ImageData);
string imgSrc = String.Format("data:image;base64,{0}", base64); //"data:image/png;base64,{0}"
return imgSrc;
}
}
}

Here is how I would create a drop down list of albums. Good luck.
Try adding an IEnumerable<SelectListItem> to your ImageViewModel for your DropdownList of Albums.
public class ImageViewModel
{
private readonly IUnitOfWork _unitOfWork;
public ImageViewModel()
{
_unitOfWork = new UnitOfWork<ApplicationDbContext>();
}
public int Id { get; set; }
public string FileName { get; set; }
public byte[] ImageData { get; set; }
public string File { get; set; }
public string Albumname { get; set; }
public string ImageSrc
{
get
{
string base64 = Convert.ToBase64String(ImageData);
string imgSrc = String.Format("data:image;base64,{0}", base64); //"data:image/png;base64,{0}"
return imgSrc;
}
}
public int AlbumId{ get; set; }
public IEnumerable<SelectListItem> Albums { get; set; } //you dropdown
}
Then in your controller, hydrate the DropdownList of Albums.
List<Album> albums = null; //get your albums from _context
var model = new ImageViewModel();
model.Albums = new SelectList(albums, "Id", "Name");
//hydrate the rest of your model..
Finally in your view, display your DropdownList of Albums.
#Html.DropDownListFor(model => model.AlbumId, Model.Albums })

Add Model In View Page:
#model IEnumerable<ImageViewModel>
then Generate DropDown:
<select id="dropdowntipo">
<option value="0">Select Item</option>
#{
foreach(var item in Model)
{
<option value= "#item.Value">#item.DisplayText</option>
}
}
</select>

You could just use ViewBag to pass data from controller to view. Assume you have Albums table in your dbContext:
public DbSet<Album> Albums{ get; set; }
1.Create Action:
public class PhotosController : Controller
{
private ApplicationDbContext _context { get; set; }
publicPhotosController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Create()
{
var model = new ImageViewModel();
ViewBag.AlbumList = _context.Albums.ToList();
return View(model);
}
}
2.Create View:
#model ImageViewModel
#*other view code*#
#Html.DropDownListFor(model => model.Albumname , new SelectList(ViewBag.AlbumList,"Name","Name"))

Related

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>

Deserialize multi-part JSON with DataContractJsonSerializer

I'm fairly new to the awesomeness that is JSON - I'm using the DataContractJsonSerializer. I cannot get the multiple instances of the Customer objects into the list.
The Attributes work as expected but there are no Customer objects in my List..??
{
"#attributes":
{"count":"2",
"offset":"0",
"limit":"100"
},
"Customer":
{
"firstName":"cust ",
"lastName":"one",
"title":"Owner",
"company":"CustOne Plants",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
"Customer":
{
"firstName":"cust ",
"lastName":"two",
"title":"Owner",
"company":"CustTwo House of Games",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
}
.NET code:
StreamReader stream = new StreamReader(#"C:\TMC Projects\PotteryManufacturing\CustomerJSON.txt");
string text = stream.ReadToEnd();
stream.Close();
byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream1 = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CustomersRoot));
var varInfo = serializer.ReadObject(stream1) as CustomersRoot;
stream1.Close();
and finally my classes/data contracts/data members:
[DataContract]
public class CustomersRoot
{
private List<Customer> m_Customers;
public CustomersRoot() { this.Customer = new List<Customer>(); }
[DataMember(Name ="#attributes")]
public Attributes attrs { get; set; }
[DataMember(Name = "Customer")]
public List<Customer> Customer
{
get { return m_Customers; }
set { m_Customers = value; }
}
}
[DataContract]
public class Customer
{
[DataMember(Name ="firstName")]
public string firstName { get; set; }
[DataMember(Name = "lastName")]
public string lastName { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "company")]
public string company { get; set; }
[DataMember(Name = "companyRegistrationNumber")]
public string companyRegistrationNumber { get; set; }
[DataMember(Name = "vatNumber")]
public string vatNumber { get; set; }
[DataMember(Name = "creditAccountID")]
public int creditAccountID { get; set; }
[DataMember(Name = "customerTypeID")]
public int customerTypeID { get; set; }
[DataMember(Name = "discountID")]
public int discountID { get; set; }
[DataMember(Name = "taxCategoryID")]
public int taxCategoryID { get; set; }
[DataMember(Name = "customerID")]
public int customerID { get; set; }
[DataMember(Name = "createTime")]
public string createTime { get; set; }
[DataMember(Name = "timeStamp")]
public string timeStamp { get; set; }
[DataMember(Name = "archived")]
public bool archived { get; set; }
}
[DataContract]
public class Attributes
{
[DataMember(Name = "count")]
public int count { get; set; }
[DataMember(Name = "offset")]
public int offset { get; set; }
[DataMember(Name = "limit")]
public int limit { get; set; }
}
I figured out what's going on here - the call can sometimes return an array of Customer objects (not formatted correctly above) OR a single instance of the object. When the web service returns a single Customer instance, the List code does not work. I will have to check on how to deal w/ this issue.

Deserialize OneNote Notebooks API Response

I'm getting an empty object when I try to Deserialize a OneNote GetAllNotebooks query.
string[] tempCapture = null;
var url = new Uri("https://graph.microsoft.com/v1.0/me/onenote/notebooks");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
tbResponse.Text = result.ToString();
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Value>));
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(tbResponse.Text.ToString()));
var obj1 = (List<Value>)ser1.ReadObject(stream1);
I'm trying to get a list of notebooks, names, links to add to a database. And my table structure matches the class below.
Here is my OneNote API class
public class Value
{
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
public string name { get; set; }
public string self { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public string id { get; set; }
public string createdTime { get; set; }
}
Here is my new code with the RootObject. I'm still getting an error. It is in the catch exception.
var test = await client.GetAsync(url);
string testStr = await test.Content.ReadAsStringAsync();
DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(RootObject));
MemoryStream testStream = new MemoryStream(Encoding.UTF8.GetBytes(testStr));
try
{
var objx = (List<RootObject>)serial.ReadObject(testStream);
}
catch(Exception ex)
{
ex.ToString();
//"There was an error deserializing the object of type OneNoteSOAP2.RootObject. End element 'createdBy' from namespace '' expected. Found element 'user' from namespace ''."
}
You can use http://json2csharp.com/. Basically, just copy the value of our JSON being returned, and use the classes generated by this website. Use RootObject to deserialize.
I ran this for you and obtained these classes:
public class OneNoteClientUrl
{
public string href { get; set; }
}
public class OneNoteWebUrl
{
public string href { get; set; }
}
public class Links
{
public OneNoteClientUrl oneNoteClientUrl { get; set; }
public OneNoteWebUrl oneNoteWebUrl { get; set; }
}
public class Value
{
public string id { get; set; }
public string self { get; set; }
public string createdTime { get; set; }
public string name { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}

Web API, C#, Json Objects, Views

I have some issues with displaying data as a Json object in this ASP.NET Web API project. It is my first try, I don't have Views, I am gonna use Postman for testing. Can you give me some diretions how to display the model as an Json Object?
//UserController
public class UsersController : ApiController
{
private LearnToLearnContext db = new LearnToLearnContext();
private BaseRepository<Users> _repository = null;
public UsersController()
{
this._repository = new BaseRepository<Users>();
}
// GET: api/Users
[ResponseType(typeof(Users))]
public IHttpActionResult GetUsers()
{
var user = _repository.GetAll();
var bindingModel = Mapper.Map<UsersBindingModels>(user);
return Ok(bindingModel);
}
}
//UserModel
public class Users
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Unique]
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public bool IsTeacher { get; set; }
public virtual List<Courses> Courses { get; set; }
}
//UserBindingModel
public class UsersBindingModels
{
[Required]
public string name { get; set; }
[Unique]
[Required]
public string email { get; set; }
[Required]
public string password { get; set; }
public bool isTeacher { get; set; }
public virtual List<Courses> Courses { get; set; }
}

Attempt to access the method failed: System.Collections.Generic.List`1..ctor()

I've this code through which I am retrieveing json data from my Localhost.But it is giving the error mentioned in my title.When I hover over the response while debugging.It shows me the correct response.I am using JSON.NET to parse json response.
var response = reader.ReadToEnd();
List<Company> cLst = JsonConvert.DeserializeObject<List<Company>>(response); //Error
this.Dispatcher.BeginInvoke(() =>
{
foreach (Company c in cLst)
{
ListBoxItemControl Li = new ListBoxItemControl();
Li.CompanyNameTextBlock.Text = c.CompanyName;
Li.PromotionTextBlock.Text = c.PromotionText;
listBox1.Items.Add(Li);
}
});
Here is the Company Class.
class Company
{
public string CompanyName {get; set;}
public string CompanySlogan { get; set; }
public string CompanyDescription { get; set; }
public string CompanyRating { get; set; }
public string CompanyDpPath { get; set; }
public string CompanyOtherInfo { get; set; }
public string CompanyFollowers { get; set; }
public int CompanyID { get; set; }
public int PromotionID { get; set; }
public string PromotionText { get; set; }
public string PromotionRating { get; set; }
public string PromotionPicPath { get; set; }
public string PromotionTitle { get; set; }
public int PromotionLikes { get; set; }
public int PromotionComments { get; set; }
}
Try making the Company class public
Take another class like,
public class RootObject
{
public List<Company> companies;
}
And then modify your code like this,
var jsonData = JsonConvert.DeserializeObject<RootObject>(response);
List<Company> cLst = jsonData.companies;
Try this and let me know.