I'm not sure if I created this topic correctly, but basically I have a number of text fields and drop downs in my view and they are arranged in such a way as to look like a row. Some of the fields include Weight, Height, Length, etc. and the fields together compose a logical item. When the user clicks on a button next to the row it dynamically creates a new row of the same textfields and dropdowns, thus adding another "item" to the form. My question is how do you get the new rows to bind to a property in the model? So for example here are the fields in the model:
[Required]
[Display(Name = "Weight")]
public string Weight { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Class")]
public string Class { get; set; }
[Required]
[Display(Name = "Number of Units")]
public string NumberOfUnits { get; set; }
[Display(Name = "Length")]
public string Length { get; set; }
[Display(Name = "Width")]
public string Width { get; set; }
[Display(Name = "Height")]
public string Height { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Type")]
public string Type { get; set; }
If the user only uses the first row this is fine since it properly maps the textfields and dropdowns to the model, but adding an additional row of these elements won't work as far as the model is concerned. Any ideas on how to get the model to bind to the dynamically created elements? Thanks.
I would recommend you the following blog post. It explains in details how to achieve this.
Related
Once again plethora of similar questions and none I can find to help me, or one I can understand.
My struggle is very simple actually. In a register form , I need to validate a few fields IF country selected from a drop down is a specific one. If not , no additional validations are needed. Let's say the country code needs to be "XX" in order to check the fields for things like length, integer or not etc.
I'm very new to MVC (less than a week) and after working with Webforms for a while, even something this simple confuses me. Anyway, here my code pieces
RegisterViewModel(only relevant fields included)
public class RegisterViewModel
{
//
[Required]
[Display(Name="Ülke")]
public string CountryCode {get; set;}
//
//[RegularExpression(#"^[0-9]*$")]
[Required]
[Display(Name = "Posta Kodu")]
public string PostCode { get; set; }
[Required]
[EmailAddress]
[Display(Name = "İrtibat E-Mail Adresi")]
public string Email { get; set; }
//regular expression and string length validations should work only if a certain country is selected
[Required]
[RegularExpression(#"^[0-9]*$")]
[StringLength(11, MinimumLength = 8, ErrorMessage = "Vergi Numarası hatalı.<br/> Lütfen kontrol ediniz.")]
[Display(Name = "Vergi No")]
public string TaxIdNo { get; set; }
//
[Required]
[Display(Name = "Firma Yetkilisi T.C. Kimlik Numarası")]
public string UserCitizenIdNo { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Firma Yetkilisi Email")]
public string UserEmail { get; set; }
[Required]
[Display(Name = "Firma Yetkilisi Tel. No.")]
public string UserPhoneNumber { get; set; }
//
}
The country dropdown
#Html.Bootstrap().DropDownListFor(t => t.CountryCode, MVCUtility.DataTableToListItem((DataTable)ViewBag.CountryList, "Code", "Name")).HtmlAttributes(new { #style = "width:100%;" })
I came across HasSelfValidation on a question but sadly noticed it is retired. How can I make these work inside an if-like construct?
PS: We set the dropdown to a specific value, I need to check if it's changed or not too.
here i have one model. now i want to buil form using html helper . so when index action will be called then i want to populate model data by hand and send the model to view.
here is my model data but the way i want to build form not being possible just due to lack of knowledge. so if possible help me
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace MvcPractise.Models
{
public class Student
{
[Required(ErrorMessage = "First Name Required")] // textboxes will show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "DOB require")] // datepicker will show
[Display(Name = "DOB :")]
[DataType(DataType.Date)]
public DateTime Dob { get; set; }
[Required(ErrorMessage = "State Required")] // drodown will show
[Display(Name = "State :")]
public List<State> State { get; set; }
[Required(ErrorMessage = "City Required")] // drodown will show
[Display(Name = "City :")]
public List<City> City { get; set; }
[Required(ErrorMessage = "Language known Required")] // group of checkboxes will show
[Display(Name = "Language known :")]
public List<Language> Language { get; set; }
[Required(ErrorMessage = "Sex Required")] // group of radio button will show
[Display(Name = "Sex :")]
public List<Sex> Sex { get; set; }
[Required(ErrorMessage = "Computer Course Required")] // listbox will show
[Display(Name = "Computer Course Done :")]
public List<ComputerCourse> ComputerCourse { get; set; }
}
public class State
{
public string ID { get; set; }
public string Name { get; set; }
}
public class City
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Language
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
public class ComputerCourse
{
public string ID { get; set; }
public string Type { get; set; }
}
}
1) for the first name & last name property i want to show textboxes
2) for the DOB property i want to show textbox with date picker
3) for the DOB property i want to show textbox with date picker
4) for the State/City property i want to show dropdown or combo
5) for the Language property i want to show group of checkboxes
6) for the Sex property i want to show 2 radio button for male & female
7) for the Computer Course property i want to show listbox
now write a index action method which will populate model with dummy data and generate UI.
when click on save button then model data will return back to action method called saved like
public ActionResult Save(Student s)
{
return View(s);
}
or
public ActionResult Save(StudentViewModel sv)
{
return View();
}
please help a newbie to learn things. thanks
Here is a good article about various types of model binding. It's not too long and demystifies the automatic binding and the manual way of doing it.
http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx
Also I would agree that this Question is a little too broad in scope. I'll try to help a little. You can use the same method name for the get and post request (The one that loads the empty page is the get, and when you fill out the form you will "post" the form data back to the post method). You will want to specify which one is using http 'get' and which one is using 'post' and you can do so with by decorating your method with an attribute like this.
[HttpGet]
public ActionResult Create()//leave it empty youre about to make it
{
var model = new ObjectType();
return view(model); // pass the new model ( empty object ) to your view;
}
[HttpPost]
public ActionResult Create(ObjectType theObject){
//MVC will try to populate the values of properties
//of theObject if they match the names on your form elements
//save it in your database
}
I have one model and one controller for multiple views.
The model have some required fields but for a specific view i need to ignore the validation for 2 specific fields.
There is any method to ignore the validation for those 2 fields?
I am using asp.net MVC3.
Model code example:
[Required(ErrorMessage = "Campul strada este obligatoriu")]
public string Strada { get; set; }
[DisplayName("Numar strada")]
[Required(ErrorMessage = "Campul strada numar este obligatoriu")]
public string NrStrada { get; set; }
For 9/10 views that is ok but for 1 view i don't want to be requiered.
When such an issue occurs then I normally create different view models. Each with it's own validation logic. There's nothing wrong with doing it this way.
Here are examples, not relating to your code, you can adjust your code accordingly.
For example with create customer I would have a create customer view model, and for edit customer I would have a edit customer view model. Each has different sets of validation. Create customer only requirs a first name and a last name. Edit customer needs a first name, last name, and employee number of who updated the customer record. Employee number updater is not required when adding a new customer.
Here is a possible create customer view model:
public class CreateCustomerViewModel
{
[Required(ErrorMessage = "Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public string LastName { get; set; }
}
Here is a possible edit customer view model:
public class EditCustomerViewModel
{
[Required(ErrorMessage = "Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Required")]
public string UpdatedByEmployeeNumber { get; set; }
}
This is just a basic example.
I am trying to update user in my model object
public ActionResult AddJob(JobQueue job,HttpPostedFileBase file)
{
job.User = "itdev";
TryUpdateModel(job)
if (ModelState.IsValid)//Always returns false
{
}
}
MODEL
public class JobQueue {
[Required]
[Display(Name="JobId")]
public string JobId { get; set; }
[Required] [Display(Name = "FileName")]
public string FileName { get; set; }
[Required]
[Display(Name = "Job Run Date")]
public DateTime JobRunDate { get; set; }
[Required]
[Display(Name = "Email")]
public string Mail { get; set; }
[Required]
[Display(Name = "User")]
public string User { get; set; }
I tried using TryUpdateModel(job) and UpdateModel(job) after assigning the values.Both of these does not seem to update the model because ModelState.IsValid return false.Can someone point me in the right directions?I am using MVC3
Thanks,
Sab
I may be wrong here, but I think job.User = "itdev"; should be sufficent to update the model without using the TryUpdateModel(job) thats how we do it in our site anyway. I have never need to use any method to actually update the model itself. Just assigned values manually.
It depends on how your model is setup I guess.
You should probably post the code for your model just in case my answer isnt helpful.
I'm trying to expand beyond the "one-to-one" mapping of models to controllers to views that most mvc(3) tutorials offer.
I have models for a person (operator) and the person's picture. In the database they would correspond to Operator and OperatorPicture tables.
public class Operator
{
public Operator()
{
this.OperatorPictures = new HashSet<OperatorPicture>();
}
[DisplayName("Operator ID")]
public int OperatorID { get; set; }
[Required]
[DisplayName("First name")]
[StringLength(20, ErrorMessage = "The first name must be 20 characters or less.")]
public string OperatorFirstName { get; set; }
[Required]
[DisplayName("Last name")]
[StringLength(20, ErrorMessage = "The last name must be 20 characters or less.")]
public string OperatorLastName { get; set; }
public virtual ICollection<OperatorPicture> OperatorPictures { get; set; } // Nav
}
public class OperatorPicture
{
[DisplayName("Operator Picture ID")]
public int OperatorPictureID { get; set; }
[DisplayName("Operator ID")]
public int OperatorID { get; set; }
[DisplayName("Picture")]
public byte[] Picture { get; set; } // 100x100
[DisplayName("Thumbnail")]
public byte[] Thumbnail { get; set; } // 25x25
public virtual Operator theoperator { get; set; } // FK
}
In most views I would present them together. A list of operators would include a thumbnail picture if it exists. Another screen might show the person's detailed information along witht the full-sized picture.
Is this where viewmodels come into play? What is an appropriate way to use them?
Thanks,
Loyd
Definitely a time for using them. ViewModels are just a way of packaging up all the different bits that go into a view or partialview.
Rather than have just the repository pattern, I have repositories and services. The service has a Get property called ViewModel, that can be called from the controller. EG:
// initialise the service, then...
return View(service.ViewModel)
You can see a more detailed description of my approach in the accepted answer for the following SO question:
MVC Patterns
Note that I am using dependency injection in that code.
It may not be a totally orthodox or canonical approach, but it results in very clean controller code and a easy to use pattern.