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>
Related
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)
I need to convert this <select id="degreemultiselect" multiple="multiple"></select to a razor control #Html.DropDownList but I am getting the error message it says "cannot convert lambda expression to type string?" is that because of the model being a list public List<DegreeModel> selectedRequesterDegrees { get; set; } is there a work around for this?
#Html.DropDownList(x => x.selectedRequesterDegrees, new { id = "degreemultiselect", #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedRequesterDegrees)
Here is a working demo:
Model:
public class Test
{
public List<DegreeModel> selectedRequesterDegrees { get; set; }
}
View:
#model Test
#Html.DropDownListFor(x => x.selectedRequesterDegrees, new SelectList(Model.selectedRequesterDegrees, "Id", "Name"), null, new { id = "degreemultiselect", #class = "form-control" })
Controller:
[HttpGet]
public ActionResult Index()
{
var model = new Test()
{
selectedRequesterDegrees = new List<DegreeModel>()
{
new DegreeModel(){ Id=1,Name="aa"},
new DegreeModel(){ Id=2,Name="bb"},
new DegreeModel(){ Id=3,Name="cc"}
}
};
return View(model);
}
Result:
I don't know why it don't save the AddressBookId form a select in my database
public class CreditCard
{
public int Id { get; set; }
[Display (Name="Customer")]
public int CustomerID { get; set; }
[Display(Name = "Billing Address")]
public int AddressBooKId { get; set; }
public virtual Customer Customer { get; set; }
}
Controller:
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "Id", "FullName");
ViewBag.CCTypeId = new SelectList(db.CreditCardTypes, "Id", "CCName");
return View();
}
public JsonResult AddList(int Id)
{
var add = from a in db.AddressBooks
where a.CustomerId== Id
select a;
return Json(new SelectList(add.ToArray(), "AddressBookId", "Address"), JsonRequestBehavior.AllowGet);
}
public IList<AddressBook> Getadd(int CustomeId)
{
return db.AddressBooks.Where(m => m.CustomerId== CustomeId).ToList();}
Mi view
<div class="form-group">
#Html.LabelFor(model => model.AddressBooKId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select><br />
#Html.ValidationMessageFor(model => model.AddressBooKId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
Json
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () {
$('#AddressBooKId').html(null)
$('#CustomerID').change(function () {
$.getJSON('/CreditCards/AddList/' + $('#CustomerID').val(), function (data) {
var items = '<option>Select a Address</option>';
$.each(data, function (i, add) {
items += "<option value='" + add.Value + "'>" + add.Text + "</option>"; });
$('#AddressBooKId').html(items);
}); }); });
</script>
Because your Dropdown is not bound with Model. You are creating it as independent control.
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select>
Change the list Id and name to "AddressBookList". Create hidden field to keep the AddressBookId using model.
#Html.HiddenFor(m => m.AddressBooKId);
Change your JS code to update the new dropdown name.
Create a new change event handler for AddressBookList and set the value of HiddenField.
$('#AddressBookList').change(function () {
$('#AddressBooKId').val($('#AddressBookList').val());
}
Now when form will be submitted the Model property AddressBookId will have the selected value.
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);
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.