I would like to automatically insert username, userid, date such thing from (server side) model in asp.net mvc how do i insert in such model ?
public class Enquiry
{
public int ID { get; set; }
public DateTime Date { get; set; }
[Required]
public string Name { get; set; }
public string Contactno { get; set; }
public string Remarks { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string Editdate { get; set; }
public string status { get; set; }
}
public class EnquiryDBContext : DbContext
{
public DbSet<Enquiry> Enquiries { get; set; }
}
How do i insert date from controller or model without having it to be inserted from view ?
my controller is like this
[HttpPost]
public ActionResult Create(Enquiry enquiry)
{
if (ModelState.IsValid)
{
db.Enquiries.Add(enquiry);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(enquiry);
}
ktm,
just populate the date in the HttpGet action and then pass that to the view. here's a snippet:
Controller:
[HttpGet]
public ActionResult Create()
{
Enquiry enquiry = new Enquiry();
enquiry.Date = DateTime.UtcNow;
// set any other required properties
return View(enquiry);
}
in your create view:
// ref to base model
#model yournamespace.Models.Enquiry
// add the date from the controller as a hidden field
#Html.HiddenFor(m => m.Date)
<!-- other properties -->
then, just use your HttpPost actionmethod as before -voila!
Related
First of all I should say my code was working fine before transferring DataAccess (Db Context & Entity classes) to class library but after transfer The value of ModelState.Isvalid return's false because the navigation property (Category) in The Review model is null.
The problem will solved by adding an nullable annotation to Category property but my question is why this problem has arisen after using class library for DataAccess.
This is my Review Model :
public class Review
{
public int Id { get; set; }
public string Author { get; set; }
[MaxLength(500)]
public string Body { get; set; }
public int Rating { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
And this is my Category Model :
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public List<Review> Review { get; set; }
}
This is my action :
public async Task<IActionResult> AddReview(Review review)
{
if (!ModelState.IsValid) return BadRequest("Enter required fields");
await _uReviewService.AddReview(review);
TempData["message"] = "success";
return RedirectToAction("Comments");
}
The issue I am having, is that if you provide a null value for an item, that is nullable, the ModelState.IsValid flags a validation error saying "The value ParentID is not valid for ParentID."
I want [int?] to allow null.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("common/menu-setting/add")]
public IActionResult AddMenuSetting(Menu model)
{
if (!ModelState.IsValid)
{
ViewData["ParentMenus"] = _commonRepository.GetParentMenus();
return View(model);
}
var returnValue = _commonRepository.AddMenu(model);
if (!returnValue)
{
return RedirectToAction("AddMenuSetting");
}
return RedirectToAction("MenuSetting");
}
Model:
public class Menu
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public int? ParentID { get; set; }
public string ParentMenuName { get; set; }
public int SortGroup { get; set; }
public int Sort { get; set; }
}
NET MVC expetrts!
I'm new in asp.NET MVC 4, so I got a simple problem not to know how to solve!
so this is my NotActivatedUsers model :
public class NotActivatedUser
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
[DefaultValue(false)]
public bool isActive { get; set; }
[Required, DataType(DataType.EmailAddress)]
public string email { get; set; }
[Required]
public string activeCode { get; set; }
public DateTime createDate { get; set; }
}
and here is my SignUp model :
public class SignUpModel
{
[Key]
public int id { get; set; }
[EmailAddress(ErrorMessage = "Invalid Email!")]
public string email { get; set; }
}
and this in my dbset:
public class Context : DbContext
{
public DbSet<NotActivatedUser> notActivatedUser { get; set; }
}
My problem is " How to use my SignUp model to insert into NotActivatedUsers Dbset?
I tried this :
public class AccountController : Controller
{
private Context db = new Context();
[HttpPost]
[AllowAnonymous]
public ActionResult SignUp(SignUpModel signUpModel)
{
if (ModelState.IsValid)
{
db.notActivatedUser.Add(signUpModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(signUpModel);
}
[AllowAnonymous]
public ActionResult SignUp()
{
return View();
}
}
I need big help from here i am new to Asp.net MVC 4 Application development , actually i faced a problem when i save my dropdownlist selected value in a database ,after i click my submit button.
I use Debug pointer to check values in a HTTP post object but it doesn't contain dropdownlist select value it always display null value in a division raw I need some expert advice to solve that problem i go through the several examples and try several times but still i haven't proper solution for that.
Model class:
public partial class tblEmployee
{
public int EmployeeId { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public Nullable<System.DateTime> DateOfJoin { get; set; }
public string Position { get; set; }
public string Office { get; set; }
public string Division { get; set; }
public Nullable<decimal> Salary { get; set; }
public virtual tblDivision Divisions { get; set; }
}
public partial class tblDivision
{
public int value { get; set; }
public string Division { get; set; }
public Nullable<int> SelectId { get; set; }
}
Controller class:
namespace EmpiteHrSystem.Controllers
{
public class EmployeeController : Controller
{
private EmpiteContext db = new EmpiteContext();
public ActionResult Create()
{
ViewBag.DivisionOptions = new SelectList(db.tblDivisions, "value","Division");
return View();
}
//
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(tblEmployee tblemployee)
{
if (ModelState.IsValid)
{
try
{
db.Entry(tblemployee).State = EntityState.Added;
db.tblEmployees.Add(tblemployee);
db.SaveChanges();
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
}
}
}
View:
#model EmpiteHrSystem.Models.tblEmployee
#{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml";}
#Html.EditorFor(model => model.EmployeeId)
#Html.ValidationMessageFor(model => model.EmployeeId)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#*#Html.EditorFor(model => model.Office)*#
#Html.DropDownList("DivisionOptions")
#Html.ValidationMessageFor(model => model.Division)
#Html.ActionLink("Back to List", "Index")
Your DivisionOptions drop down list is not being bound back to the model properly because it is the wrong name. Your model is looking for a property with the name Division while your drop down list is being bound to DivisionOptions. You have a few options.
Use a strongly typed helper
#Html.DropDownListFor(x=>x.Division, (SelectList)ViewBag.DivisionOptions)
Rename your currrent code and pass in the SelectList
#Html.DropDownList("Division", (SelectList)ViewBag.DivisionOptions)
In a ASP.NET MVC3 Razor project I have 2 Models
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Contents { get; set; }
public int Author { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Post.Author field links to Author.Id field
In a view, I need to display list of
Post.Title
Post.Contents
Author.Name
How to display the information joining (from) both models?
Note : I guess I need to use a ViewModel and bind the view with IEnumerable List, but I have no idea how to select the data from both models
You can create a viewmodel which will have ONLY properties which u want to be displayed on view
public class PostViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Contents { get; set; }
public string AuthorName { get; set; }
}
You populate this viewmodel with your data in your controller action taking necessary joins
public ActionResult GetAuthorInfor()
{
var query = //context.Post join with context.Author
Select new PostViewModel()
{
Id = post.id,
Title = post.title,
Contents = post.contents,
AuthorName = author.authorname
}
return view(query.Single());
}
and create a typed view to render this model.
Model Post.cs:
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Contents { get; set; }
public int AuthorID { get; set; }
public virtual Author Author { get; set; }
}
Model Author.cs :
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
DBContext Class:
public class SampleDB : DbContext
{
public DbSet<Author> Authors{ get; set; }
public DbSet<Post> Posts{ get; set; }
}
I.Way(using direkt view)
you can use on View like this :
Samp.Models.SampleDB dbPosts = new Samp.Models.SampleDB();
foreach (var post in dbPosts.Posts.ToList())
{
string post_Title = post.title;
string post_Contents = post.Contents;
string author_Name = post.Author.Name;
}
II.Way (Using via Controller) -Recommended-
you can use on Controller like this :
Samp.Models.SampleDB db = new Samp.Models.SampleDB();
public ActionResult Index()
{
return View(db.Posts.ToList());
}
Using this on View:
#model IEnumerable<Samp.Models.Post>
foreach (var post in Model.Posts.ToList())
{
string post_Title = post.title;
string post_Contents = post.Contents;
string author_Name = post.Author.Name;
}