In Model.State Validation is invalid - file-upload

i trying to upload the multiple images using asp.netcore mvc. i made property of pic in which i save the url path of image. when compiler hits the Model.State it gives Validation invalid. i also created property image in which image url saved. that property type is IFORMFILE. i am using sql to save pic information and using model for code. when i check in model state i find the error message of pic field is required.
namespace ehouse.Controllers
{
public class AddPropertyRentController1 : Controller
{
Rentdb DB =new Rentdb();
private IWebHostEnvironment _IWebHostEnvironment;
public AddPropertyRentController1(IWebHostEnvironment IWebHostEnvironment)
{
_IWebHostEnvironment = IWebHostEnvironment;
}
public IActionResult aprent()
{
return View();
}
[HttpPost]
public IActionResult aprent([Bind] RentModel ar)
{
if (ar.imge1 != null)
{
string folder = "photos/photo/";
folder += ar.imge1.FileName + Guid.NewGuid().ToString();
ar.pic1 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge1.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge2 != null)
{
string folder = "photos/photo/";
folder += ar.imge2.FileName + Guid.NewGuid().ToString();
ar.pic2 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge2.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge3 != null)
{
string folder = "photos/photo/";
folder += ar.imge3.FileName + Guid.NewGuid().ToString();
ar.pic3 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge3.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge4 != null)
{
string folder = "photos/photo/";
folder += ar.imge4.FileName + Guid.NewGuid().ToString();
ar.pic4 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge4.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge5 != null)
{
string folder = "photos/photo/";
folder += ar.imge5.FileName + Guid.NewGuid().ToString();
ar.pic5 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge5.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge6 != null)
{
string folder = "photos/photo/";
folder += ar.imge6.FileName + Guid.NewGuid().ToString();
ar.pic6 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge6.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge7 != null)
{
string folder = "photos/photo/";
folder += ar.imge7.FileName + Guid.NewGuid().ToString();
ar.pic7 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge7.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge8 != null)
{
string folder = "photos/photo/";
folder += ar.imge8.FileName + Guid.NewGuid().ToString();
ar.pic8 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge8.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge9 != null)
{
string folder = "photos/photo/";
folder += ar.imge9.FileName + Guid.NewGuid().ToString();
ar.pic9 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge9.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge10 != null)
{
string folder = "photos/photo/";
folder += ar.imge10.FileName + Guid.NewGuid().ToString();
ar.pic10 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge10.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
try
{
if (ModelState.IsValid)
{
string res = DB.Saverecord(ar);
string pics = DB.imagedb(ar);
TempData["msg"] = res;
}
}
catch (Exception ex)
{
TempData["msg"] = ex.Message;
}
return View();
}
}
}
RentModel
using System.ComponentModel.DataAnnotations;
namespace eHouse.Models
{
public class RentModel
{
public int id { get; set; }
public string tittle { get; set; }
public string price { get; set; }
public string descrip { get; set; }
public string areaUnit { get; set; }
public int area { get; set; }
public string province { get; set; }
public string city { get; set; }W
public string stadress { get; set; }
//public string features { get; set;}
public string bathroom { get; set; }
public string furnished { get; set; }
public string p_type { get; set; }
public string bedroom { get; set; }
public int p_id { get; set; }
[Required]
public string? pic1 { get; set; }
[Required]
public IFormFile imge1 { get; set; }
[Required]
public string? pic2 { get; set; }
public IFormFile imge2 { get; set; }
[Required]
public string? pic3 { get; set; }
public IFormFile imge3 { get; set; }
[Required]
public string? pic4 { get; set; }
public IFormFile imge4 { get; set; }
[Required]
public string? pic5 { get; set; }
public IFormFile imge5 { get; set; }
[Required]
public string? pic6 { get; set; }
public IFormFile imge6 { get; set; }
[Required]
public string? pic7 { get; set; }
[Required]
public IFormFile imge7 { get; set; }
[Required]
public string? pic8 { get; set; }
public IFormFile imge8 { get; set; }
[Required]
public string? pic9 { get; set; }
public IFormFile imge9 { get; set; }
[Required]
public string? pic10 { get; set; }
public IFormFile imge10 { get; set; }
public int r_id
{
get; set;
}
}
}

Related

How to insert the file name in the database using Ado.Net? Instead of the file name null value is being inserted

How to insert the file name in the database using Ado.Net? Instead of the file name null value is being inserted
CONNECTION CODE-
public bool AddBooks(LibraryManagementModel LibraryObject)
{
SqlCommand cmd = new SqlCommand("AddBooks", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#book_id", LibraryObject.Id);
cmd.Parameters.AddWithValue("#book_name", LibraryObject.Book_Name);
cmd.Parameters.AddWithValue("#author", LibraryObject.Author);
cmd.Parameters.AddWithValue("#publisher", LibraryObject.Publisher);
cmd.Parameters.AddWithValue("#date_of_publication", LibraryObject.Date_of_publication);
cmd.Parameters.AddWithValue("#year", LibraryObject.Year);
cmd.Parameters.AddWithValue("#category", LibraryObject.Category);
cmd.Parameters.AddWithValue("#price", LibraryObject.Price);
cmd.Parameters.AddWithValue("#image",LibraryObject.Image);
if (connection.State == ConnectionState.Closed)
connection.Open();
int i = cmd.ExecuteNonQuery();
connection.Close();
if (i > 1)
{
return true;
}
else
{
return false;
}
}
CONTROLLER CODE-
public ActionResult AddBooks(LibraryManagementModel LibraryObject)
{
string fileName = Path.GetFileNameWithoutExtension(LibraryObject.ImageFile.FileName);
string extension = Path.GetExtension(LibraryObject.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
LibraryObject.Image = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
LibraryObject.ImageFile.SaveAs(fileName);
if (ModelState.IsValid == true)
{
BooksDB.AddBooks(LibraryObject);
ModelState.Clear();
ViewBag.AddMsg = "<script>('Data Saved')</script>";
return RedirectToAction("Index");
}
else
{
ViewBag.AddMsg = "<script>('something went wrong')</script>";
return RedirectToAction("Index");
}
return View();
}
MODEL CODE-
public class LibraryManagementModel
{
public int Id { get; set; }
[Required]
public string Book_Name { get; set; }
[Required]
public string Author { get; set; }
[Required]
public string Publisher { get; set; }
[Required]
[DataType(DataType.Date)]
public string Date_of_publication { get; set; }
[Required]
public string Year { get; set; }
public string Category { get; set; }
public string Price{ get; set; }
[DisplayName("Upload Book Image")]
public string Image { get; set; }
public HttpPostedFileBase ImageFile { get; set; }
}

Why is my Viewmodel that I am returning to my POST method in MVC returning a null ViewModel

I really thought I understood what I was doing, but here goes. I decided I need more properties in my View so I created a ViewModel called ViewDataset and replaced the original Dataset model in the View. On my HttpGet TestDataset the View Model is populated correctly with data from the Viewmodel:
My original dataset that was working is below:
public class Dataset
{
public int Dataset_ID { get; set; }
public int Category_ID { get; set; }
public string Provider { get; set; }
public string Name { get; set; }
public string Institution { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public bool Domestic { get; set; }
public bool International { get; set; }
public bool Includes_PHI { get; set; }
public bool PHI_Limited { get; set; }
public bool Includes_PIL { get; set; }
public bool PIL_Limited { get; set; }
public bool Citation_Requirements { get; set; }
public string Citation_Comments { get; set; }
public Nullable<System.DateTime> Availability_Beg_DT { get; set; }
public Nullable<System.DateTime> Availability_End_DT { get; set; }
public bool Subscription_Renewal { get; set; }
public Nullable<System.DateTime> Subscription_Renewal_DT { get; set; }
public bool Retention_Expiry { get; set; }
public Nullable<System.DateTime> Retention_Expiry_DT { get; set; }
public bool Data_Destruction { get; set; }
public Nullable<System.DateTime> Data_Destruction_DT { get; set; }
public string Data_Destruction_Instructions { get; set; }
public Nullable<int> Contract_ID { get; set; }
public bool Draft_Status { get; set; }
public bool Admin_Only { get; set; }
public string Dataset_Alias { get; set; }
public bool Loc_Amazon { get; set; }
public bool Loc_IT_Research { get; set; }
public bool Loc_Research_Proj { get; set; }
public bool Loc_Secure_Data { get; set; }
public bool Loc_Mercury { get; set; }
public bool Loc_Research_CC { get; set; }
public bool Loc_Research_VM { get; set; }
public bool Loc_External { get; set; }
public bool Access_Url { get; set; }
public bool Access_Download_App { get; set; }
public bool Access_Lab_Terminal { get; set; }
public bool Access_Email_Req { get; set; }
public bool Access_File_Download { get; set; }
public bool Access_Other { get; set; }
public string Location_Notes { get; set; }
public string Access_Notes { get; set; }
public Nullable<System.DateTime> Date_Added { get; set; }
public Nullable<System.DateTime> Date_Modified { get; set; }
public string Added_By_User { get; set; }
public string Updated_By_User { get; set; }
public bool External_Collaborators
{
get; set;
}
}
Here is my new ViewDataset (viewmodel)
public class ViewDataset
{
public Dataset dataset;
public List<SelectListItem> categories_list;
}
Here is my is a sample of my view ... couple of lines, but the view is populated correctly with data from the ViewDataset model
#model ResearchDataInventoryWeb.Models.ViewDataset
<td>
#Html.TextBoxFor(model => model.dataset.Institution, new { placeholder = "<Institution>", #class = "input-box" })
</td>
<td>
#Html.TextBoxFor(model => model.dataset.Name, new { placeholder = "<Dataset Name>", #class = "input-box" })
</td>
#Html.CheckBoxFor(model => model.dataset.Domestic) <span class="display-checkbox">Domestic</span>
#Html.CheckBoxFor(model => model.dataset.International) <span class="display-checkbox">International</span>
#Html.CheckBoxFor(model => model.dataset.Includes_PHI) <span class="display-checkbox">Includes PHI </span>
#Html.CheckBoxFor(model => model.dataset.Includes_PIL) <span class="display-checkbox">Includes PII </span><br />
#Html.CheckBoxFor(model => model.dataset.External_Collaborators) <span class="display-checkbox">External Collaborators Allowed (Sharable)</span>
#Html.CheckBoxFor(model => model.dataset.Citation_Requirements) <span class="display-checkbox">Citation Requirements</span>
<input type="submit" value="TestPost" />
Here is my HttpPost TestDataset : The model Viewdataset (dataset, categories_list) properties that I am passing back from the view are NULL, am I missing something?
[HttpPost]
public ActionResult TestDataset(ViewDataset viewdataset)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:4251/");
//HTTP POST
viewdataset.dataset.Category_ID = 2;
viewdataset.dataset.Dataset_ID = 1;
viewdataset.dataset.Location = "Fingers Crossed";
viewdataset.dataset.Institution = "Not Null";
var dataset = viewdataset.dataset;
// var postTask = client.PostAsJsonAsync<Dataset>("api/datasets/1", dataset);
var postTask = client.PostAsJsonAsync("api/datasets/1", dataset);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(viewdataset);
}
Here if my HttpGet TestDataset in case you need to see it
public async Task<ActionResult> TestDataset()
{
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
List<Dataset> dataset = new List<Dataset>();
List<Category> categories = new List<Category>();
var parm = "1";
var returned = new Dataset();
var ViewDataset = new ViewDataset();
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("api/Datasets/" + parm);
HttpResponseMessage Res2 = await client.GetAsync("api/Categories");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
returned = JsonConvert.DeserializeObject<Dataset>(EmpResponse);
}
if (Res2.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var CatResp = Res2.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
categories = JsonConvert.DeserializeObject<List<Category>>(CatResp);
}
// Create the Categories Select List
var categoryList = new List<SelectListItem>();
foreach (Category c in categories)
{
categoryList.Add(new SelectListItem
{
Value = c.Category_ID.ToString(),
Text = c.Description,
Selected = (c.Category_ID == returned.Category_ID ? true : false)
});
}
ViewDataset.dataset = returned;
ViewDataset.categories_list = categoryList;
//returned.External_Collaborators = returned.External_Collaborators == null || false ? false : true;
//returning the employee list to view
return View(ViewDataset);
}
}
Try to change
public class ViewDataset
{
public Dataset dataset;
public List<SelectListItem> categories_list;
}
to
public class ViewDataset
{
public Dataset dataset { get; set; }
public List<SelectListItem> categories_list { get; set; }
}

How to avoid saving a value of property of form object when saving changes to db

In a crud asp.net core 2.2 web app, I need to avoid saving a property of form object to db. How do I do that?
I've tried using [Editable(false)] data annotation on the ListBin property to prevent saving property value to db.
[Table("supply_lists")]
public partial class SupplyLists
{
[Column("id")]
public int Id { get; set; }
[Column("category_id")]
public int CategoryId { get; set; }
[Required]
[Column("coursecode")]
[StringLength(200)]
public string Coursecode { get; set; }
[Required]
[Column("title")]
[StringLength(200)]
public string Title { get; set; }
[Required]
[Column("filename")]
[StringLength(200)]
public string Filename { get; set; }
[Column("isactive")]
public bool Isactive { get; set; }
[Column("date", TypeName = "smalldatetime")]
public DateTime Date { get; set; }
[Column("list_bin")]
public byte[] ListBin { get; set; }
[ForeignKey("CategoryId")]
[InverseProperty("SupplyLists")]
public virtual SupplyListCategory Category { get; set; }
}
[ModelMetadataType(typeof(MetaDataTypeModel))]
public partial class SupplyLists
{
}
public class MetaDataTypeModel
{
[Editable(false)]
public byte[] ListBin { get; set; }
[Display(Name = "Is Active")]
public bool Isactive { get; set; }
[Display(Name ="Course Code")]
public string Coursecode { get; set; }
[Display(Name = "Category")]
public int CategoryId { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
}
public class EditModel : PageModel
{
private readonly SupplyListCore22.Models.SupplyListsContext _context;
private readonly IHostingEnvironment _env;
public EditModel(SupplyListCore22.Models.SupplyListsContext context, IHostingEnvironment env)
{
_context = context;
_env = env;
}
[BindProperty]
public SupplyLists SupplyLists { get; set; }
[BindProperty]
public FileUpload FileUpload { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
SupplyLists = await _context.SupplyLists
.Include(s => s.Category).FirstOrDefaultAsync(m => m.Id == id);
if (SupplyLists == null)
{
return NotFound();
}
ViewData["CategoryId"] = new SelectList(_context.SupplyListCategory, "Id", "Category");
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
//if (!ModelState.IsValid)
//{
// return Page();
//}
_context.Attach(SupplyLists).State = EntityState.Modified;
await _context.SaveChangesAsync();
if (FileUpload.UploadSupplyList != null)
{
var fileUploadData = await utilities.utilities.ProcessFormFile(FileUpload.UploadSupplyList, ModelState);
if (ModelState.ErrorCount > 0)
{
ViewData["CategoryId"] = new SelectList(_context.SupplyListCategory, "Id", "Category");
return Page();
}
var sl = _context.SupplyLists.Find(SupplyLists.Id);
sl.ListBin = fileUploadData;
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
It set the ListBin to null in db which is not what I wanted when saving changes (I wanted to preserve the old value of ListBin in db).

json string downloaded with mising values c# webclient

I'm conding a rent car asp.net mvc application and I have a strange problem.
I used the skyscanner api to get the available cars list but the json string downloaded is always missing the attribute cars or there is cars that exist and are available.
string datacar = "";
String ch = "http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/" + ids + "/" + ide + "/" + dstart + "T" + tstart + "/" + dend + "T" + tend + "/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1";
Uri url = new Uri(ch);
// Uri url2 = new Uri("http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/27539733/27539733/2016-09-10T17:45/2016-09-17T17:45/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1");
CarModel model = new CarModel();
// for (int i = 0; i <= 20; i++)
// {
using (WebClient wc = new WebClient())
{
wc.Headers.Set("Content-Type", "application/json");
datacar = wc.DownloadString(url);
//datacar = wc.DownloadString(url2);
model = JsonConvert.DeserializeObject<CarModel>(datacar);
}
and here it is the carModel defintion
namespace carrent.Models
{
public class SubmittedQuery
{
public string market { get; set; }
public string currency { get; set; }
public string locale { get; set; }
public string pickup_place { get; set; }
public string dropoff_place { get; set; }
public string pickup_date_time { get; set; }
public string drop_off_date_time { get; set; }
public string driver_age { get; set; }
}
public class Image
{
public int id { get; set; }
public string url { get; set; }
}
public class CarClass
{
public int id { get; set; }
public int sort_order { get; set; }
public string name { get; set; }
}
public class DebugItem
{
public string type { get; set; }
public string title { get; set; }
public string content { get; set; }
}
public class CarModel
{
public SubmittedQuery submitted_query { get; set; }
public List<object> cars { get; set; }
public List<object> websites { get; set; }
public List<Image> images { get; set; }
public List<CarClass> car_classes { get; set; }
public List<DebugItem> debug_items { get; set; }
}
}
Ps: the strange thing in this problem is when I initialize an url (the url2) the code run perfectly
please guys help me to get the solution and thanks

How to filter audio podcasts from iTunes Search API?

By searching for podcasts with the iTunes API (http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html) the result contains both audio and video podcasts. Is there any way to retrieve only audio podcasts from the API?
Thanks in advance :-)
From the documentation it doesn’t seem as if filtering audio and video podcasts is possible; however, you could loop through the resulting items and check whether each item is audio or video for filtering. You can do that be finding additional information from the RSS feed or by making another call to iTunes using the subscribePodcast url (see example).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using System.IO;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//Searching for Windows Weekly
string url = "https://itunes.apple.com/search?term=Windows%20Weekly&media=podcast&attibute=audio";
string json = FetchHTML(url);
JavaScriptSerializer s = new JavaScriptSerializer();
var result = s.Deserialize(json);
var audioOnly = new List();
foreach (var item in result.Results)
{
if (!IsVideo(item.TrackId))
{
audioOnly.Add(item);
}
}
foreach (var au in audioOnly)
{
Console.WriteLine(au.TrackName);
}
Console.ReadLine();
}
static bool IsVideo(string id)
{
string req = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/subscribePodcast?id=" + id + "&wasWarnedAboutPodcasts=true";
string xml = FetchHTML(req,true);
bool isVideo = false;
var re = XElement.Load(new StringReader(xml)).Elements("dict").Elements("dict");
bool next = false;
foreach (var e in re.Elements())
{
if (next)
{
//This is the is video value
isVideo = e.Name.LocalName.Trim().ToLower() == "true";
next = false;
break;
}
if (e.Value == "is-video")
{
next = true;
}
}
return isVideo;
}
static string FetchHTML(string url,bool doItAsITunes = false)
{
string htmlCode = "";
using (WebClient client = new WebClient())
{
if (doItAsITunes)
{
client.Headers.Add("user-agent", "iTunes/9.1.1");
}
htmlCode = client.DownloadString(url);
}
return htmlCode;
}
}
public class SearchResult
{
public SearchResult()
{
Results = new List();
}
public int ResultCount { set; get; }
public List Results { set; get; }
}
public class Item
{
public Item()
{
GenreIDs = new List();
Genres = new List();
}
public string WrapperType { set; get; }
public string Kind { set; get; }
public string ArtistID { set; get; }
public string CollectionID { set; get; }
public string TrackId { set; get; }
public string ArtistName { set; get; }
public string CollectionName { set; get; }
public string TrackName { set; get; }
public string CollectionCensoredName { set; get; }
public string TrackCensoredName { set; get; }
public string ArtistViewUrl { set; get; }
public string FeedUrl { set; get; }
public string TrackViewUrl { set; get; }
public string PreviewUrl { set; get; }
public string ArtworkUrl60 { set; get; }
public string ArtworkUrl100 { set; get; }
public float CollectionPrice { set; get; }
public float TrackPrice { set; get; }
public string CollectionExplicitness { set; get; }
public string TrackExplicitness { set; get; }
public string DiscCount { set; get; }
public string DiscNumber { set; get; }
public string TrackCount { set; get; }
public string TrackNumber { set; get; }
public string TrackTimeMillis { set; get; }
public string Country { set; get; }
public string Currency { set; get; }
public string PrimaryGenreName { set; get; }
public List GenreIDs { set; get; }
public List Genres { set; get; }
}
}
Yes. In regular serach you get everything:
https://itunes.apple.com/search?term=jack+johnson
But you can add some params to request for example (for your case)
&entity=song
So the request will be:
https://itunes.apple.com/search?term=jack+johnson&entity=song
For more look at Searching seaction in this docs