DropdownList selected value not saved in database - asp.net

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)

Related

Html.DropDownList razor

I'm new to MVC and C# and having hard time with a dropdown list.
What I'm trying to accomplish is to initialize my page with an object that keeps the settings.
(I read settings from XML file).
Here's what I have
public class StoreSettings
{
public String BackSrs2Path { get; set; }
public int NoLines { get; set; }
public String Requesturl { get; set; }
}
public class Store
{
public String StoreId { get; set; }
public String Address { get; set; }
public StoreSettings StoreSettings { get; set; }
}
and the Model for my view page is a list of Store
#model System.Collections.Generic.List<Control2.Models.Store>
#{
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (var Store in Model)
{
SelectListItem i = new SelectListItem();
i.Text = Store.StoreId;
i.Value = Store.StoreId;
selectList.Add(i);
}
}
#using (Html.BeginForm())
{
SelectList list = new SelectList(selectList, "Value", "Text");
#Html.DropDownList("ddl", list, "select store", new { onchange = "this.form.submit();" });
}
}
By reading examples here managed to populate the dropdownlist from my model and postsback
but now i need to get only the selected object from the list and apply his seetings to the page to display it etc a message "you ve selected Store"+Storeid(the slected from dropdown)
Also this code is written in my cshtml page which isn't the best but couldn't figure how should I do it with ViewModel and dropdown list
Yes when I first started looking at the DropDownList Binding mechanisms of MVC I too had problems. What I'd like to do is suggest to you the following:
Create a Viewmodel and bind the entire view to the viewmodel... as follows:
public class VMStore
{
public VMStore()
{
ItemsInDropDown = new List<SelectListItem>(){
new SelectListItem{ Text="SomeValue", Selected=false, Value="SomeUniqueId"}
};
}
public String StoreId { get; set; }
public String Address { get; set; }
public StoreSettings StoreSettings { get; set; }
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> ItemsInDropDown { get; set; }
public void Post()
{
//This method will have the user selected value...
}
}
The view will bind fields like this:
#model WebApplication1.ViewModels.VMStore
#{
ViewBag.Title = "GetStore";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetStore</h2>
<div>
<h4>VMStore</h4>
<hr />
<dl class="dl-horizontal">
#Html.BeginForm(){
<dt>Select Store</dt>
<dd>#Html.DropDownListFor(p=>Model.SelectedValue, Model.ItemsInDropDown) </dd>
<dd><button type="submit">Submit</button></dd>
}
</dl>
</div>
The action methods will look like this:
public ActionResult GetStore()
{
return View();
}
[HttpPost]
public ActionResult GetStore(ViewModels.VMStore userdata) {
if (ModelState.IsValid)
{
userdata.Post();
}
return View(userdata);
}

MVC 5 Multiple Models in a Single View

Could somebody please provide an example of how to combine two models within one view?
Currently I have a page called RecordCard which contains:
#model IEnumerable<WebApplication1.Models.Weight>
This is provided by the following code in the AccountController:
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
return View(weightModel);
}
The RecordCard page also contains a form which is bound to the following class:
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
However, these are two individual models with different purposes, so how do I combine to a single model that contains an IEnumerable list and set of form elements that will ultimately post to the AccountController correctly to add a record to the database using the following code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(Weight Model)
{
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return View(Model);
}
I have included the Weight class below:
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
Also here is the WebApplication1Entities class which declares the Weight table as Weights:
public partial class WebApplication1Entities : DbContext
{
public WebApplication1Entities()
: base("name=WebApplication1Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Weight> Weights { get; set; }
}
Please explain what needs to be modified and how, no matter what I try to read, follow and implement, I seem to be missing something.
Any help would be much appreciated :-)
I would say this is good example of using ViewModel here. I would suggest something like -
Create ViewModel with the composition of the two classes
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
....
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
.....
public class WeightViewModel
{
public IList<AddWeightModel> AddWeightModel { get; set; }
public Weight Weight { get; set; }
}
Then change your view to accept the view models -
#model WeightViewModel
Finally modify your controller to cope with the change -
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
var viewModel = new WeightViewModel
{
Weight = weightModel,
AddWeightModel = new List<AddWeightModel>(){}
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(WeightViewModel viewModel)
{
Weight Model = viewModel.Weight;
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return RedirectToAction("RecordCard");
}
I've tackled this before, can came to an elegant solution.
First, you'd want to setup your main classes to send, as well as a 'holder' class to store them to eventually send to a view.
As you probably found out, this is because a view can't have multiple models sent to it.
public class WebsiteTheme
{
public string Color { get;set; }
public string Title { get;set; }
public WebsiteTheme() {
Color = "blue";
Title = "test website";
}
}
public class User
{
public string Name { get;set; }
public string Gender { get;set; }
public User() {
Name = "Anonymous";
Gender = "Unspecified";
}
}
public class ToPage
{
public WebsiteTheme WebsiteTheme{ get; set; }
public User User { get; set; }
public ToPage() {
websiteTheme = new WebsiteTheme();
user = new User();
}
}
This will allow you to send any amount of classes to your page.
Then, in your controller, you'd want to populate those classes. Make sure to initialise them all first, then set the populated classes to your holder class.
WebsiteTheme websiteTheme = new WebsiteTheme();
websiteTheme.Color = "orange";
User user = new User();
user.Name = "Darren";
ToPage toPage = new ToPage();
toPage.User = user;
toPage.WebsiteTheme = websiteTheme;
return View(toPage);
In your view, you'd call them in any way you want to. But make sure to use HolderModel.SpecifiedModel in every case.
#model WebApplication1.Models.ToPage
#Html.DisplayFor(model => model.User.Name)
I did a compound model like this:
public class CompoundModel
{
public SearchModel SearchModel { get; set; }
public QueryResultRow ResultModel { get; set; }
}
public class QueryResultRow
{
[DisplayName("Id")]
public long id { get; set; }
[DisplayName("Importdatum")]
public System.DateTime importdate { get; set; }
[DisplayName("Mandant")]
public int indexBMClient { get; set; }
}
public class SearchModel
{
[Required]
[DataType(DataType.Date)]
[Display(Name = "Zeitraum von")]
public DateTime dateFrom { get; set; }
[Display(Name = "Terminal-ID")]
public string tid { get; set; }
[Display(Name = "Belegnummer")]
public string receiptnumber { get; set; }
}
In the view header:
#model MyProject_aspmvc.Models.CompoundModel
And get data access from the SearchModel, for example:
model => model.SearchModel.tid
and data access from the ResultModel, for example:
model => model.ResultModel.importdate

EditorForModel/DisplayForModel Rendering Nothing

I have a very basic problem in MVC 4. I am trying to use the "EditorForModel" to render a simple form, but the HTML is always blank (no Exception, nothing).
ViewModel:
public class ProjectViewModel {
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public string Client { get; set; }
public bool Secured { get; set; }
public DateTime StartDate { get; set; }
}
Controller Action:
[HttpGet]
public ActionResult New() {
return View(new ProjectViewModel());
}
View:
#model BuMan.ViewModels.ProjectViewModel
#{ Html.EditorForModel();}
I am obviously missing something very obvious, but shouldn't that render some default inputs for each property?!
You should remove curlybraces around Html.EditorForModel.
Your view should be
#model BuMan.ViewModels.ProjectViewModel
#Html.EditorForModel()

ASP.NET MVC 3 Model null on submit

View
#model Survey.Models.TakeSurveyViewModel
#{
Layout = "~/Views/Shared/_SiteLayout.cshtml";
}
<h2>SURVEY : #Model.Title</h2>
<h3>#Model.Description</h3>
<hr />
#using (Html.BeginForm("SubmitSurvey", "HomePage", FormMethod.Post, new { id = "surveyForm" }))
{
for (int index = 0; index < Model.SurveyQuestions.Count; index++)
{
#* Editor Template - Null result *#
#*SurveyQuestionModel item = Model.SurveyQuestions[index];
#Html.EditorFor(x => item);*#
<p>#Model.SurveyQuestions[index].QuestionText</p>
#Html.DropDownListFor(item => Model.SurveyQuestions[index].OptionId, new SelectList(Model.SurveyQuestions[index].Options, "OptionId", "OptionText"), string.Empty)
}
<input type="submit" value="SubmitSurvey" />
}
ViewModel
public class TakeSurveyViewModel
{
public string Title { get; set; }
public string Description { get; set; }
public int SurveyId { get; set; }
public List<SurveyQuestionModel> SurveyQuestions { get; set; }
public TakeSurveyViewModel() { }
public TakeSurveyViewModel(int surveyId)
{
//Populate data - works ok.
}
}
DropDownList Model
public class SurveyQuestionModel
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
[Required(ErrorMessage = "Please select an option.")]
public int OptionId { get; set; }
public IEnumerable<QuestionOption> Options { get; set; }
}
The page is rendering fine, with all the drop-downs with correct options. The id and name of each select is also unique -
id="SurveyQuestions_3__OptionId" name="SurveyQuestions[3].OptionId"
Controller Action
[HttpPost]
public ActionResult SubmitSurvey(TakeSurveyViewModel model)
{
return !ModelState.IsValid ? TakeSurvey(model.SurveyId) : null;
}
But clicking on the submit button, controller action model is null.
Edit: Removed the 2x HTML.BeginForm
Edit 2: SurveyQuestions now has public setter. The issue seem to be still there. Please see this image:
Is the problem that you have SurveyQuestions being a private set?
-old answer-
You have 2 x
(Html.BeginForm(Html.BeginForm
I once forgot to have my form within a using statement which did the same sort of thing.

Entering data from asp.net mvc

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!

Resources