Bind data from db to dropdownlist + ASP.NET MVC - mysql

I have a question about using a dropdownlist in ASP.net MVC.
This is my situation:
Create view:
#using (Html.BeginForm("Create", "Deliverable", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EventViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Thumbnail)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Thumbnail, new { type = "file" })
#Html.ValidationMessageFor(model => model.Thumbnail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Image , new {type="file"})
#Html.ValidationMessageFor(model => model.Image)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VideoUrl)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.VideoUrl)
#Html.ValidationMessageFor(model => model.VideoUrl)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VideoUrl)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.VideoUrl)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
After the 'VideoURL' I would like to have a Dropdownlist with values that are stored in my database. Most of the tutorials that I find don't bind the values in the dropdownlist to the database.
I insert the values in my db in my backoffice so I can't insert them in frontoffice...
This is my Controller:
public ActionResult Create(DeliverableViewModel model)
{
var afstudeerrichtingen = (repository.GetAfstudeerrichtingen()).ToList();
if (ModelState.IsValid)
{
try
{
MemoryStream target = new MemoryStream();
model.Image.InputStream.CopyTo(target);
byte[] data = target.ToArray();
model.Thumbnail.InputStream.CopyTo(target);
byte[] datatwo = target.ToArray();
users usr = userrepo.FindByUsername(User.Identity.Name);
model.UsernameID = usr.user_id;
repository.AddDeliverable(model.Title, model.Description, model.UsernameID, data, datatwo, model.VideoUrl, model.Afstudeerrichting);
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
return View(model);
}
In sent the values to my repository where I save it in my database.
This is my DeliverableViewModel:
public class DeliverableViewModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Thumbnail")]
public HttpPostedFileBase Thumbnail { get; set; }
[Required]
[Display(Name = "Image")]
public HttpPostedFileBase Image { get; set; }
[Required]
[Display(Name = "VideoUrl")]
public string VideoUrl { get; set; }
[Required]
[Display(Name = "AfstudeerrichtingID")]
public int AfstudeerrichtingID { get; set; }
[Required]
[Display(Name = "Afstudeerrichting")]
public IEnumerable<SelectListItem> Items { get; set; }
public long UsernameID { get; set; }
}
Does anyone know what I have to add in my view & controller to make this work?
The values are in my tabel "Afstudeerrichtingen" in my mysql database
- afstuddeerichting_id
- afstudeerrichting_name

Add a dropdownlist in your view:
#Html.DropDownListFor(model => model.AfstudeerrichtingID,
new SelectList(ViewBag.Richtingen,
"AfstudeerrichtingId", "AfstudeerrichtingName"))
Add your Afstudeerrichting collection to the ViewBag in the controller:
ViewBag.Richtingen = afstudeerrichtingen;
Assuming that that collection contains the properties AfstudeerrichtingId and AfstudeerrichtingName, as used in the view.
Another thing to do is change your AfstudeerrichtingID to string, and translate it to/from int in your repository class.

Related

Getting null values while Remote Validating CurrentPassword

I have a currentPassword property in my changePasswordViewModel and i want to validate it on client side using Remote attribute. this is my model
public class PatientPasswordChangeViewModel
{
public int id { get; set; }
[Required(ErrorMessage ="field is required")]
[DataType(DataType.Password)]
[Remote("IsCorrectPassword", "Patient", ErrorMessage ="Password is incorrect")]
[Display(Name ="Current Password")]
public string OldPassword { get; set; }
[Required(ErrorMessage ="field is required")]
[StringLength(100, ErrorMessage = "The {0} must be atleast {2} characters long", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string NewPassword { get; set; }
[Required(ErrorMessage ="field is required")]
[DataType(DataType.Password)]
[Compare("NewPassword",ErrorMessage ="Password Does Not Match")]
[Display(Name = "Confirm Password")]
public string ConfirmNewPassword { get; set; }
}
this is RemoteValidation Code in the controller
public JsonResult IsCorrectPassword([Bind(Prefix = "PatientPasswordChangeViewModel.OldPassword")] string OldPassword, [Bind(Prefix = "PatientPasswordChangeViewModel.id")] int id)
{
var getUserName = context.Patients.Where(q => q.p_id == id).Select(q => q.UserName).FirstOrDefault();
var getPassword = context.SiteUsers.Where(q => q.UserName == getUserName).Select(q => q.PasswordHash).FirstOrDefault();
bool status;
if (PasswordHashManager.ValidatePassword(OldPassword, getPassword))
{
status = true;
}
else
{
status = false;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
And this is the View Code
<section class="password_change-body">
<h2 id="passheading">Change Password</h2>
#using (Html.BeginForm("ChangePassword", "Patient", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.HiddenFor(model => model.id)
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.OldPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OldPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OldPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NewPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmNewPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmNewPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmNewPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="change" class="btn btn-primary" />
</div>
</div>
</div>
}
</section>
I've tried
public JsonResult IsCorrectPassword([Bind(Prefix = "PatientPasswordChangeViewModel")] string OldPassword, [Bind(Prefix = "PatientPasswordChangeViewModel")] int id)
public JsonResult IsCorrectPassword(PatientPasswordChangeViewModel model)
although i'm getting the password value but value for property id is always null. how can i get the value of id.
EDIT
I got it working by using AdditionalValues in Remote Attribute used it in my method.
[Remote("IsCorrectPassword", "Patient", ErrorMessage ="Password is incorrect",AdditionalFields ="id")]
and in my controller method
public JsonResult IsCorrectPassword(string OldPassword, int id)

How to add dropdown YearID in current model section

What I need
I need to add drop down and LabelFor YearID and add from model Year to
current model section with Formate bootstrap as (Replace departID WITH YearID).
I work in MVC 5 visual studio 2015 and i need to get drop down list from another model .
Current model name is Section:
namespace UniversityData.Models
{
[Table("Section")]
public partial class Section
{
public Section()
{
}
[Key]
public int SecID { get; set; }
[Required]
[StringLength(50)]
public string SecName{ get; set; }
[ForeignKey("Department")]
[DisplayName("DepartmentName")]
public int departID { get; set; }
}
}
My code to drop down departID inside my current model section with bootstrapis:
<div class="form-group">
#Html.LabelFor(model => model.departID, "DepartmentName", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("departID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.departID, "", new { #class = "text-danger" })
</div>
</div>
Another model Year I want to generate dropdown to it
[Table("Year")]
public partial class Year
{
public Year()
{
this.department = new HashSet<Department>();
}
[Key]
public int YearID { get; set; }
[Required]
[StringLength(50)]
public string YearName { get; set; }
}
}
what i try as following :
<div class="form-group">
// how to add labelfor replace of text
YearName:
<div class="col-md-10">
#Html.DropDownList("YearID", null, htmlAttributes: new { #class = "form-control" })
</div>
</div>
I get error :
{"DataBinding: 'System.Data.Entity.DynamicProxies.Department_3D49A8148DA2B6C2F8801CE72951BF7FDBF82503B3A52665397F8B7058E3F8A8' does not contain a property with the name 'YearName'."}
Thank you I solved my problem
The problem found in action :
ViewBag.YearID = new SelectList(db.years.ToList(), "YearID", "YearName");
before it found as db.departments.ToList() so that error come after i change departments to years problem solved because drop down for years not department .
And in view i do as following :
<div class="form-group">
#Html.Label("YearName", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("YearID", null, htmlAttributes: new { #class = "form-control" })
</div>
</div>

Extra parameter is coming with a POST

My model is this a Movie class with this metadata:
[MetadataType(typeof(MovieMetadata))]
public partial class Movie
{
}
class MovieMetadata
{
[ScaffoldColumn(false)]
public int id { get; set; }
[Required(ErrorMessage = "Title is required")]]
[StringLength(70, ErrorMessage = "Title must have a lenght less than 70")]
public string title { get; set; }
[Required(ErrorMessage = "The realese date of the movie is required")]
public DateTime releaseDate { get; set; }
public string storyline { get; set; }
public Binary poster { get; set; }
[ScaffoldColumn(false)]
public Binary trailer { get; set; }
}
My Create View has this code inside:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createForm", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="gallMemberBox">
<div class="rightFormContent">
<div>
#Html.LabelFor(model => model.title)
#Html.EditorFor(model => model.title)
#Html.ValidationMessageFor(model => model.title)
</div>
<div>
#Html.LabelFor(model => model.releaseDate)
#Html.EditorFor(model => model.releaseDate)
#Html.ValidationMessageFor(model => model.releaseDate)
</div>
<div>
#Html.Label("Poster")
<input name="poster" value="C:" id="poster" type="file" />
</div>
<div>
#Html.Label("Trailer")
#* #Html.TextBox("trailer", "", new { type = "file", id="trailer" })*#
<input name="trailer" value="" id="trailer" type="file" />
</div>
<div>
#Html.LabelFor(model => model.storyline)
#Html.TextAreaFor(model => model.storyline, new{id="storyline"})
</div>
<div>
#Html.Label("Directors")
<select class="chosen-select" multiple="" data-placeholder="Select directors">
#for(int i = 0; i < directors.Count; i ++)
{
<option value="#i">#directors[i].name</option>
}
</select>
</div>
<div>
#Html.Label("Actors")
<select class="chosen-select" multiple="" data-placeholder="Select actors of the Screen">
#for(int i = 0; i < actors.Count; i ++)
{
<option value="#i">#actors[i].name</option>
}
</select>
</div>
<div>
#Html.Label("Writers")
<select class="chosen-select" multiple="" data-placeholder="Select writers of the Film">
#for(int i = 0; i < writers.Count; i ++)
{
<option value="#i">#writers[i].name</option>
}
</select>
</div>
<input type="submit" value="Create" />
</div>
}
I just filled title and releaseDate and click on submit(Create), after that in my ModelState I have three parameters, title, releaseDate and storyline(I never put some value on this one, and the value is an empty string. On the others fields I never put a value and they do not come with that POST. Why? And how to fix this?
public ActionResult Create([Bind(Exclude = "poster, trailer")]Movie movie, HttpPostedFileBase poster, HttpPostedFileBase trailer)
{
Your field storyline will already be available by the id and name "storyline as this is created like by MVC.
Remove the "id" part, or use "#id = ...".
You can write:
<div>
Storyline
#Html.TextAreaFor(model => model.storyline)
</div>

save data from dropdown list in create or edit action

This is my Model.
public class Territory
{
[Display(Name = "ID", ResourceType = typeof(Resources.Resource))]
public long ID { get; set; }
[Display(Name = "Name", ResourceType = typeof(Resources.Resource))]
public string Name { get; set; }
[Display(Name = "Code", ResourceType = typeof(Resources.Resource))]
public string Code { get; set; }
[Display(Name = "ProviderKey", ResourceType = typeof(Resources.Resource))]
public string ProviderKey { get; set; }
[Display(Name = "Provider", ResourceType = typeof(Resources.Resource))]
public string Provider { get; set; }
[Display(Name = "Countries", ResourceType = typeof(Resources.Resource))]
public virtual IList<Country> Countries { get; set; }
[Display(Name = "Rights", ResourceType = typeof(Resources.Resource))]
public IList<RightApplication> Rights { get; set; }
}
This is my Controller Edit action.
public ActionResult Edit(long id) {
var territory = new db.Territories.FindAsync(id);
if(territory == null) return HttpNotFound();
ViewBag.Countries = new SelectList(db.Countries.AsEnumerable(), "ID", "Name");
return View("Edit", territory);
}
And this is my Index view.
#foreach (var item in Model.Items)
{
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-1">
<h4 class="pull-right" style="margin:4px;"><i class="fa fa-edit"></i>-<i class="fa fa-trash-o"></i></h4>
<div class="panel panel-success territory panel-scroll">
<div class="panel-heading">#item.Name</div>
<div class="panel-body">
<ul class="list-group">
#foreach (var country in item.Countries)
{
<li class="list-group-item">#country.Name</li>
}
</ul>
</div>
</div>
</div>
}
This is my Create View.
#using (Html.BeginForm(htmlAttributes: new { #class = "form single-col" }))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code)
#Html.EditorFor(model => model.Code)
#Html.ValidationMessageFor(model => model.Code)
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProviderKey)
#Html.EditorFor(model => model.ProviderKey)
#Html.ValidationMessageFor(model => model.ProviderKey)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Provider)
#Html.EditorFor(model => model.Provider)
#Html.ValidationMessageFor(model => model.Provider)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Countries)
#Html.DropDownList("Countries")
</div>
<div class="form-group">
<div class="controls">
<div class="btn-group">
#if (Model.ID == 0)
{
<button type="submit" class="btn btn-primary"><i class="fa fa-plus"></i> Create</button>
}
else
{
<button type="submit" class="btn btn-primary"><i class="fa fa-pencil"></i> Update</button>
}
<a class="btn btn-info" href="#Url.Action("Index")"><i class="fa fa-arrow-left"></i> Back to List</a>
</div>
</div>
</div>
}
I'm trying Country select from DropdownList to show in Index view.I have get Territory Name in index view,but i'm not able to add Country Name in Territory.
there are 2 ways to save the data from the drop down. The first is a little more work and isn't as reliable. Look at the rendered drop down and if there isn't a name on it, add one
#Html.DropDownList("Countries", Model.CountriesList, new { name = "Country" })
with that on your controller you can get the selected value by
Request.Form["Country"].ToString();
the way I would recommend is to change your drop down to a for helper
#Html.DropDownListFor(x => x.Country, Model.CountriesList)
this will tie the selected value to your model (Country in this case) which you can then pull out in your post method

Pass variable to strongly typed form from different view

I'm having a little trouble passing url variables to a form on a separate view. Basically I have a 'HomeController' which has a 'Contact' action and view, and a 'SalesController' which has an action and a view called 'View'.
On the view called 'View' (confusing I know), I have an action link like so:
<a href="#Url.Action("Contact", "Home", new { pid = Model.Property[0].Pid, type = "Viewing"})" class="detailsBtn">
As you can see, this is passing two variables of 'pid' and 'type' to the 'Contact' action of the 'HomeController'. The contact returns a strongly typed view with the following model being used.
public class ContactModel
{
[Required]
[DataType(DataType.Text)]
public string FullName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Phone(ErrorMessage = "Invalid Phone Number")]
public string Telephone { get; set; }
[DataType(DataType.Text)]
public string Address { get; set; }
[Required]
[DataType(DataType.Text)]
public string Subject { get; set; }
[Required]
[DataType(DataType.Text)]
public string Message { get; set; }
}}
Here's the Contact view:
#using (Html.BeginForm())
{
<div class="formField">
<span class="label">Full Name *</span><br />
#Html.TextBoxFor(Model => Model.FullName, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.FullName, "Full enter your full name")<br/>
</div>
<div class="formField">
<span class="label">Email Address *</span><br />
#Html.TextBoxFor(Model => Model.Email, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Email, "Please ensure that a valid email is entered.")<br/>
</div>
<div class="formField">
<span class="label">Telephone *</span><br />
#Html.TextBoxFor(Model => Model.Telephone, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Telephone, "Please enter a valid telephone number")<br/>
</div>
<div class="formField">
<span class="label">Property Address (optional)</span><br />
#Html.TextBoxFor(Model => Model.Address, new {#class = "txtContact" })<br />
</div>
<div class="formField">
<span class="label">Subject *</span><br />
#if (ViewBag.Pid != null) {
#Html.TextBoxFor(Model => Model.Subject, new {#class = "txtContact" })
} else {
#Html.TextBoxFor(Model => Model.Subject, new { #class = "txtContact" })
}
#Html.ValidationMessageFor(Model => Model.Subject, "Please enter a subject")<br/>
</div>
<div class="formField">
<span class="label">Message *</span><br />
#Html.TextAreaFor(Model => Model.Message, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Message, "Please enter a message")<br/>
</div>
<input type="submit" class="contact-btn" value="Send" />
}
I simply need to know the best way for me to add the 'pid' and 'type' variables passed to the Contact Action from the Action link in the Sales Controller as values for my text boxes in the contact form.
You can always extend your Model to include a PID and Type property.
In your form you could just enter #Html.HiddenFor(Model => model.Pid) and #Html.HiddenFor(Model => model.Type) (or #Html.DisplayFor if you want them visible)
If you didn't want to do that, you could put your PID and Type values into ViewBag or ViewData from the Action, and then put these values into form fields in your view.
Edit:
If you would like the Pid and Type to be part of your strongly typed view, you can change your model to be like the following:
public class ContactModel
{
//all your other properties...
public string ContactType { get; set; }
public string Pid { get; set; }
}
Then in your Contact action, you can:
var model = new ContactModel() { ContactType = type, Pid = pid };
return View(model);