Dropdown list with items from database in MVC - c#

I have this 2 models
public class FileType
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("FileType")]
public int FileTypeID { get; set; }
}
And tables with data in PostgreSQL database for these models, i want to create 2 dropdownlists in view with Name for filetype and name for genre.I want to create that 2 ddl in this upload view
public class FileUploadViewModel
{
public List<FileModel> Files { get; set; }
public string Name { get; set; }
public string Extension { get; set; }
public string Description { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public string FilePath { get; set; }
public string PublishedOn { get; set; }
public int DownloadCounter { get; set; }
}

If you want to create a dropdown list for FileTypeID, you could try this:
(...)
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("FileType")]
public FileType FileTypeID { get; set; }
}
public enum FileType
{
Item1,
Item2,
Item3,
Item4
}
Then, in your view:
#model YourNameSpace.Models.Genre
#{
ViewData["Title"] ="xyz";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.DropDownListFor(m => m.FileTypeID, new SelectList(Enum.GetValues(typeof(FileType))), "Select FileType", new { #class = "form-control" })
You will then see a dropdown list with the four selectable items item1-item4 and a default placeholder stating "Select FileType".

Related

Partial View not binding with the model

I have main view binding to custom model with two partial views. One partial view is binding to schedule model and other to the same custom model.
The second partial view is showing null on http posting.
This is the Main View
#model DBS.CustomVariable
<div id="divSchedule" style="display: none" align="left">
#Html.Partial("_cron", new DBS.Schedule2())
#Html.Partial("ScheduleEditPartial" ,Model)
</div>
The view model is like this
namespace DBS
{
public class CustomVariable
{
public int ReportId { get; set; }
public string ReportName { get; set; }
public string ReportTypeId { get; set; }
public string TemplateLocation { get; set; }
public bool IsScheduled { get; set; }
public int ScheduleID { get; set; }
public string MailCC { get; set; }
public string MailBCC { get; set; }
public string MailSubject { get; set; }
public string MailBody { get; set; }
public string MailTo { get; set; }
public bool Status { get; set; }
public bool IsReportNameOverwrite { get; set; }
public string NamingConvention { get; set; }
public string FileAttribs { get; set; }
public string[] DirectoryName { get; set; }
public List<string> FolderName { get; set; }
public string SavePath { get; set; }
[RegularExpression("^[a-zA-Z][a-zA-Z0-9_]*$", ErrorMessage = "Please start with alphabets followed by alphanumeric or _.")]
[StringLength(20)]
public string FilePath { get; set; }
public string DefaultLocation => ConfigurationManager.AppSettings["DefaultExcelReportSavePath"];
public int ShareOption { get; set; }
public string[] station_arr { get; set; }
public string TemplateOriginalName { get; set; }
}
}
And the controller is this
[ValidateInput(false)]
[System.Web.Mvc.HttpPost]
[Authorize(Roles = "ExcelCreate")]
[SessionExpireFilter]
public ActionResult Create(FormCollection form, HttpPostedFileBase file, CustomVariable modelCustomVariable)
{......}
I am getting null values in the customvariable in controller method.
Where am i missing?

How to get team entities details in other main entities in MVC 5?

I have two entities Team, MainEntry. Now I want to get all team details in dropdown while entring in MainEntry view
in MVC.
In other word in the MainEntry views I want get all team details in the dropdown.
Im using VS-2015, MVC5, EF6 with Code first migration.
public class Team
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public string TeamAge { get; set; }
public string TeamLocation { get; set; }
}
public class MainEntry
{
public int MainEntryId { get; set; }
public string TeamAssignment { get; set; }
public string Role { get; set; }
public string Series { get; set; }
public string Stock { get; set; }
public string Points { get; set; }
public sting Teamname {get; set;} //(dropdown fill)
public string Teamage {get;set;} //(dropwon fill)
public string TeamLocation {get;set;} //(dropwon fill)
}
You can populate your dropdown list like
ViewBag.Teamnames = _db.Team.Select(c => new SelectListItem
{
Text = c.Teamname ,
Value = c.MainEntryId.ToString(),
Selected = true
});
and in your view:
#Html.DropDownList(
"TeamName",
(IEnumerable<SelectListItem>)ViewBag.Teamnames,
new { style = "max-width: 600px;" }
)
Another way
I usually create a view model that contains both the model if you want collection in model you can change your model as below and update your migration configuration file
public class MainEntry {
public int MainEntryId { get; set; }
public string TeamAssignment { get; set; }
public string Role { get; set; }
public string Series { get; set; }
public string Stock { get; set; }
public string Points { get; set; }
public IEnumerable<Team> Teamname { get; set; }//(dropwon fill)
public IEnumerable<Team> Teamage //(dropwon fill)
public IEnumerable<Team> TeamLocation //(dropwon fill) }

Populating a page with data from a database in mvc 5

I would like to populate certain parts of a view with certain fields from a database. I'm not sure exactly how to make this work. This is my current situation...
Here is my controller action:
public ActionResult Course_page(string id)
{
string abbrev = id;
var cpage = from c in db.Course_page
select c;
if (!String.IsNullOrEmpty(abbrev))
{
cpage = cpage.Where(x => x.abbrev.Contains(abbrev));
}
return View(cpage);
}
My Model:
[Table("course_page")]
public class Course_page
{
[Key]
public int CourseID { get; set; }
public string Meta { get; set; }
public string Title { get; set; }
public string Country { get; set; }
public string main_image { get; set; }
public string list_1 { get; set; }
public string list_2 { get; set; }
public string list_3 { get; set; }
public string list_4 { get; set; }
public string list_5 { get; set; }
public string list_6 { get; set; }
public string list_7 { get; set; }
public string list_8 { get; set; }
public string list_9 { get; set; }
public string list_10 { get; set; }
public string testim_1 { get; set; }
public string testim_2 { get; set; }
public string testim_3 { get; set; }
public string course_site { get; set; }
public string popup_script { get; set; }
public string abbrev { get; set; }
}
The view (shortened):
#model IEnumerable<oltinternational_mvc.Models.Course_page>
<div id="main_container">
<article class="content">
<h1>{#Html.DisplayNameFor(modelItem => cpage.Title)}</h1>
</article>
</div>
I get that I have to reference the cpage variable somewhere on the view but I'm not sure exactly in what manner. The idea is that the course page will load with the correct details as per the ID provided by the URL.
Please could someone advise me how I am to include the cpage variable in the view file or if I am doing this the correct way at all?
You are doing it correct way just change this helper :
{#Html.DisplayNameFor(modelItem => cpage.Title)} to
#Html.DisplayNameFor(modelItem => modelItem .Title)
And print the data in foreach loop because you can have more than one result.

IList dataset insert to database table

I'm getting data set to POST action method's model object like following
Once I expand above object , it has following properties
Once I expand above ListProductFields IList , it has following properties
Once I expand above ListProductFields IList's object values , [0]th value it has following properties and its values
this is the relevant model class files
public class AddNewProduct
{
public string Product_ID { get; set; }
public string ProductTypeID { get; set; }
public string ProductCategoryID { get; set; }
public string Subsidary_ID { get; set; }
public string Field_ID { get; set; }
public string ProductFieldNameEn { get; set; }
public string ProductFieldNameAr { get; set; }
public string ApprovalStatus { get; set; }
public string Status { get; set; }
public IList<AB_ProductTypeCategoryField> ListProductFields { get; set; }
}
public partial class AB_ProductTypeCategoryField
{
public string ProductFieldID { get; set; }
public string ProductFieldNameEn { get; set; }
public string ProductFieldNameAr { get; set; }
public string ProdcutFieldDiscriptionEn { get; set; }
public string ProductFieldDiscriptionAr { get; set; }
public string Status { get; set; }
public bool IsChecked { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public string UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
public string Field_Value_EN { get; set; }
public string Field_Value_AR { get; set; }
}
public partial class AB_Product_vs_Field
{
public string Product_ID { get; set; }
public string Field_ID { get; set; }
public string Field_Value_EN { get; set; }
}
I have database table call AB_Product_vs_Field and I want to insert ,
ProductFieldID ,Field_ID , Field_Value_EN from those values from last image
since these are 19 objects have to insert to the AB_Product_vs_Field database table I may have to use a loop .
so I created following linq query to insert data to that table
[HttpPost]
[ValidateInput(false)]
public ActionResult Add_Product(AddNewProduct product)
{
AB_Product_vs_Field insertproductvalue = new AB_Product_vs_Field();
if (ModelState.IsValid)
{
for (int i = 0; i < product.ListProductFields.Count; i++)
{
insertproductvalue.Product_ID = product.Product_ID;
insertproductvalue.Field_ID = product.ListProductFields[i].ProductFieldID;
insertproductvalue.Field_Value_EN = product.ListProductFields[i].Field_Value_EN;
};
db.AB_Product_vs_Field.Add(insertproductvalue);
db.SaveChanges();
}
}
but I'm getting following error
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I put debug point in front of this line db.AB_Product_vs_Field.Add(insertproductvalue); of my code.once this line calling its directing to following section in App_Browsers.9u0xu-_o.0.cs file
public class ApplicationBrowserCapabilitiesFactory : System.Web.Configuration.BrowserCapabilitiesFactory {
public override void ConfigureCustomCapabilities(System.Collections.Specialized.NameValueCollection headers, System.Web.HttpBrowserCapabilities browserCaps) {
}
this is the error page I'm getting once this line called
these are the images of error
Image 1:
Image 2:
I added the following line in the for loop, then it can keep a record of every tuple
#Html.HiddenFor(m => m.ListProductFields[i].ProductFieldID)
then my view page appeared like this
<div class="col-md-10">
#Html.HiddenFor(m => m.ListProductFields[i].ProductFieldID)
#Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_EN,
new { #class = "form-control summernote", #row = 5 })
</div>

How to define model property for master detail

I have a post model that for every post it's need to define category and tag , and from category or tag I wanna to reach all of posts that have that category of tag.
this is my blog model
public class Post
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string Summary { get; set; }
public DateTime CreationDate { get; set; }
public string UrlSlug { get; set; }
public Category Category { get; set; }
public Tag Tag { get; set; }
}
and this is Category:
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
public string UrlSlug { get; set; }
public string Description { get; set; }
public DateTime CreationDate { get; set; }
public IList<Post> Posts { get; set; }
}
and finally this tag model:
public class Tag
{
public Guid Id { get; set; }
public string Name { get; set; }
public string UrlSlug { get; set; }
public string Description { get; set; }
public DateTime CreationDate { get; set; }
public IList<Post> Posts { get; set; }
}
I just want to know what I've done in designing model is right or not ??
You dont need the lists in the model ( remove public IList Posts { get; set; }
First create two get actions in the controller that takes tag ID, and the other`category ID. Inside the this actions get all the posts and populate your View ( detail view)
public ActionResult PostsByCategoryID(Guid Id)
{
List<post> posts = ///get them by id
return View(posts) ; //the view take list and displays the posts
}

Categories