Multiple views same model[MVC 3] - asp.net-mvc-3

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.

Related

The required column was not present in the results of a 'FromSql' operation

I've just starting learning MVC6 with EF7. I have a stored proc that I'd like to return a portion of the fields that are in my model. If I don't return every field in my model, I'm getting "The required column 'FirstName' was not present in the results of a 'FromSql' operation".
Is there a way to get make some columns not required so I can return just a portion of the fields in my model?
model:
public class LoginViewModel
{
[Key]
public int UserID { get; set; }
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Protected ID")]
public string ProtectedID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
My proc for testing:
CREATE PROCEDURE [dbo].[aaa_TopXXUsersTest]
#NumToReturn int = 10
AS
BEGIN
SET NOCOUNT ON;
select top(#NumToReturn) UserID, LastName, Username,Password, ProtectedID from Users where Deleted = 0
END
and last, my controller code:
public IActionResult Index()
{
var user = _context.Set<LoginViewModel>().FromSql("dbo.aaa_TopXXUsersTest #NumToReturn = {0}", 20);
return View(user);
}
If I include all the fields of my model in my stored proc the call work fine, but I can't seem to return just a subset. Is there a way to make some of the fields not required?
Used [NotMapped] attribute with first name.
The NotMappedattribute can be applied to properties of an entity class for which we do not want to create corresponding columns in the database.
public class LoginViewModel
{
[Key]
public int UserID { get; set; }
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Protected ID")]
public string ProtectedID { get; set; }
[NotMapped]
public string FirstName { get; set; }
public string LastName { get; set; }
}
this means that the column 'FirstName' is not being returned in the result set.
Do a 'SELECT * FROM TABLE' to solve the issue.
It requires a Id column to be returned from the SP.
select top(#NumToReturn) 0 AS 'Id', UserID, LastName, Username,Password, ProtectedID
from Users
where Deleted = 0
Or Change UserID to Id from select and model
Try removing this public string FirstName { get; set; }. Your stored procedure is not returning the value for Firstname field, but you are trying to accept it in your loginViewModel class in this string Firstname variable.
To addition current answers:
According to last version, FromSql changed. Instead of that we can use eather FromSqlRaw or FromSqlInterpolated
As mentioned in docs: FromSqlInterpolated is similar to FromSqlRaw but allows you to use string interpolation syntax. Just like FromSqlRaw, FromSqlInterpolated can only be used on query roots.
We can achieve excluding property from mapping, using OnModelCreating method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Ignore<Property>(); //property needed to be excluded
}
or: [NotMapped] attribute

MVC 5 Conditional Validation

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.

How to bind form with model data in MVC

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
}

update modelobject in a controller

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.

MVC 3 Binding Dynamic View Data to Model

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.

Resources