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.
Related
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
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.
Good Day guys!
I've just started using MVC3, I've 2 models in my application i.e. "Page" and "PageHistory" both has same properties. except that "PageHistory" has one extra property called "PageId" which references the "Page" model.
My question is am doing it in correct way? or should I use inheritance for this.
If inheritance is a option, How can I handle this, any examples will help me a lot.
My Model looks like as follows:
public class Page
{
private readonly IndianTime _g = new IndianTime();
public Page()
{
CreatedOn = _g.DateTime;
Properties = "Published";
Tags = "Page";
RelativeUrl = string.Empty;
}
public string Path
{
get { return (ParentPage != null) ? ParentPage.Heading + " >> " + Heading : Heading; }
}
[Key]
public int Id { get; set; }
[StringLength(200), Required, DataType(DataType.Text)]
public string Title { get; set; }
[StringLength(200), Required, DataType(DataType.Text)]
public string Heading { get; set; }
[MaxLength, Required, DataType(DataType.Html)]
public string Content { get; set; }
[Display(Name = "Reference Code"), ScaffoldColumn(false)]
public string ReferenceCode { get; set; }
[Required]
[Remote("CheckDuplicate", "Page", ErrorMessage = "Url has already taken", AdditionalFields = "initialUrl")]
public string Url { get; set; }
[Display(Name = "Created On"), ScaffoldColumn(false)]
public DateTime CreatedOn { get; set; }
//Parent Page Object (Self Reference: ParentId = > Id)
[Display(Name = "Parent Page")]
public int? ParentId { get; set; }
[DisplayFormat(NullDisplayText = "Root")]
public virtual Page ParentPage { get; set; }
public virtual ICollection<Page> ChildPages { get; set; }
}
I don't think inheritance will be the right way, the current structure looks ok to me.
See if you choose to make the Page as parent, and Pagehistory as being inherited from Page which actually it is not its just the pagehistory quite simply put.
Your idea of inheritance should always come from real world implementations, for ex. there could be diff. kinds of pages all inheriting from a Super Page type, while Page history is just a property to the page rather a complex property with properties inside it.
In my ASP.Net mvc3 Razor project i have to implement date validation.My format for the same was dd-mm-yyyy.i tried in different way but none works fine .I need a simple one.My question is is there any regular expression for the same.
My Model Code
{
[Table("tbl_Employee")]
public class Employee
{
[Key]public int EmpId { get; set; }
[Required(ErrorMessage="Employee First Name is Required")]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(ErrorMessage="Employee Last Name is Required")]
public string LastName { get; set; }
public int Age{get;set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
public string Address { get; set; }
public string Position { get; set; }
public string Department { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfJoining { get; set; }
public string EducationalQuali { get; set; }
public string Experience { get; set; }
public string Others { get; set; }
}
View Code
<div class="col-lg-10" >#Html.TextBoxFor(model => model.DateOfBirth, new { #class = "form-control", placeholder = "Date/Month/Year" })</div>
I have used one placeholder to show the user that ""this was the format".But it is also creating problem from the user.how to solve this?
You can decorate the model property with RegularExpression Attribute Class with the following pattern,
^(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /](19|20)[0-9][0-9]$
It will validate following date formats,
dd/MM/yyyy
dd-MM-yyyy
The property value will be set valid if it satisfies the pattern. You can set the custom error message in ErrorMessage property.
[RegularExpression("^(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /](19|20)[0-9][0-9]$", ErrorMessage="")]
public DateTime DateOfBirth { get; set; }
This works well on both server and client side. For client side which is better for good user experience, do not forget to turn on the unobtrusive validation and include jquery.validation.js and jquery.validation.unobtrusive.js in your web page. :)
I have the properties for two entities in a ViewModel. The two entities are both related to one another, so for example, User and Posts. Each User can have multiple Posts, and Many Posts can belong to a single user (one-to-many).
The aim from my ViewModel is to allow the addition of a User and a Post on the same form. So my ViewModel looks something like this:
public class CreateVM
{
[Required, MaxLength(50)]
public string Username { get; set; }
[Required, MaxLength(500), MinLength(50)]
public string PostBody { get; set; }
// etc with some other related properties
}
In my Controller on the Create Method I have something like this:
[HttpPost]
public ActionResult Create(CreateVM vm)
{
if (ModelState.IsValid)
{
User u = new User()
{
Username = vm.Username,
// etc populate properties
};
Post p = new Post()
{
Body = vm.PostBody,
// etc populating properties
};
p.User = u; // Assigning the new user to the post.
XContext.Posts.Add(p);
XContext.SaveChanges();
}
}
It all looks fine when I walk through it through the Debugger, but when I try to view the post, its User relationship is null!
I also tried
u.Posts.Add(p);
UPDATE:
My Post class code is as follows:
public class Post
{
[Key]
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public User User { get; set; }
}
But that also did not work. What am I doing wrong?
Problem is that EF can not lazy load the User property because you haven't made it virtual.
public class Post
{
[Key]
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public virtual User User { get; set; }
}
If you know beforehand that you are going to access the User property of the post you should eager load the User related to the post.
context.Posts.Include("User").Where(/* condition*/);