Using Automapper to Edit selected fields of a model MVC4 - asp.net-mvc-4

I am trying to update selected fields using a viewmodel(OApplyIDViewModel) of the original model(OApply). When I run changes are not effected. I will appreciate help from anyone who is experienced with this. I do not get any error. The form submits and redirects.
I have this at global.asax
AutoMapper.Mapper.CreateMap<OApplyIDViewModel, OApply>();
This is ViewModel
public class OApplyIDViewModel
{
[Key]
public int OAId { get; set; }
[Display(Name = "Identification")]
[Required(ErrorMessage = "Identification Required")]
public int IdId { get; set; }
[Display(Name = "Identification Number")][Required(ErrorMessage="ID Number Required")]
public string AIdentificationNo { get; set; }
[Display(Name = "Licence Version(5b)")]
[RequiredIf("IdId", Comparison.IsEqualTo, 1, ErrorMessage = "Version(5b) Required")]
public string ALicenceVersion { get; set; }
public int CountryId { get; set; }
[RequiredIf("IdId",Comparison.IsNotEqualTo,1, ErrorMessage="Country Required")]
[Display(Name = "Your Electronic Signature Date Seal")]
[Required(ErrorMessage="Date Signature Seal Required")]
public DateTime SigDate { get; set; }
[ScaffoldColumn(false)]
[Display(Name = "Last Updated on")]
public DateTime UDate { get; set; }
[ScaffoldColumn(false)]
[Display(Name = "Last Updated by")]
public String UDateBy { get; set; }
}
This is at Controller
//GET
public ActionResult ClientEditID(int id)
{
var model = new OApplyIDViewModel();
OApply oapply = db.OApply.Find(id);
if (model == null )
{
return HttpNotFound();
}
ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "CountryName", model.CountryId);
ViewBag.IdId = new SelectList(db.PhotoIds, "IdId", "IdName", model.IdId);
return View();
}
[HttpPost]
public ActionResult ClientEditId(OApplyIDViewModel oapply, int Id)
{
if (!ModelState.IsValid)
{
return View(oapply);
}
var onlineid = db.OApply.Where(x => x.OAId == Id).FirstOrDefault();
Mapper.Map<OApplyIDViewModel,OApply>(oapply);
oapply.UDateBy = Membership.GetUser().ProviderUserKey.ToString();
oapply.UDate = DateTime.Now;
db.Entry(onlineid).State= EntityState.Modified;
db.SaveChanges();
ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "CountryName", oapply.CountryId);
ViewBag.IdId = new SelectList(db.PhotoIds, "IdId", "IdName", oapply.IdId);
return RedirectToAction("HomeAccount");
}
This is the View
#using (Html.BeginForm("ClientEditId", "OApply", FormMethod.Post, new { enctype = "multipart/form-data", #class = "stdform" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>OnlineApplication</legend>
#Html.HiddenFor(model => model.OAId)
<div class="related">
<div class="editor-label">
#Html.LabelFor(model => model.IdId, "IdType")
</div>
<div class="editor-field">
#Html.DropDownList("IdId", String.Empty)
#Html.ValidationMessageFor(model => model.IdId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AIdentificationNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AIdentificationNo)
#Html.ValidationMessageFor(model => model.AIdentificationNo)
</div>
<div class="requiredfields">
<div class="editor-label">
#Html.LabelFor(model => model.ALicenceVersion)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ALicenceVersion)
#Html.ValidationMessageFor(model => model.ALicenceVersion)
</div>
</div>
<div class="country">
<div class="editor-label">
#Html.LabelFor(model => model.CountryId)
</div>
<div class="editor-field">
#Html.DropDownList("CountryId")
#Html.ValidationMessageFor(model => model.CountryId)
</div>
</div></div>
<div class="editor-label">
#Html.LabelFor(model => model.SigDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SigDate)
#Html.ValidationMessageFor(model => model.SigDate)
</div>
<p>
<input type="submit" value="Save" />
</p>

There is something wrong here:
var onlineid = db.OApply.Where(x => x.OAId == Id).FirstOrDefault();
-> Mapper.Map<OApplyIDViewModel,OApply>(oapply);
oapply.UDateBy = Membership.GetUser().ProviderUserKey.ToString();
oapply.UDate = DateTime.Now;
db.Entry(onlineid).State= EntityState.Modified;
The line with the arrow returns a new OApply instance. It does not update onlineid. In fact, it has no idea about onlineid. Try the following.
Mapper.Map<OApplyIDViewModel,OApply>(oapply, onlineid);
Now it will modify onlineid instead of returning one. However, you should ignore the mapping for the primary key if it is an identity (auto-incrementing) one.
AutoMapper.Mapper.CreateMap<OApplyIDViewModel, OApply>()
.ForMember(dest => dest.OAId, opt => opt.Ignore());
I am not sure if OAId is your primary key or not. You are not following naming conventions and probably some other conventions too, at all.
I have made corrections in your code :
public ActionResult ClientEditID(int id)
{
OApply oapply = db.OApply.Find(id);
->if (oapply == null )
{
return HttpNotFound();
}
->var model = Mapper.Map<OApply, OApplyIDViewModel>(oapply);
ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "CountryName", model.CountryId);
ViewBag.IdId = new SelectList(db.PhotoIds, "IdId", "IdName", model.IdId);
->return View(model);
}
Your HttpPost is mostly valid, except that you put data into ViewBag before you use RedirectToAction(). That data will be lost. Instead, use TempData dictionary. Check msdn.

Related

Not updating ID

i am new to asp.net and i have a question. I have created a simple form fro sending sms, however my id always stays null. Can you please advise on what am i doing wrong? I used exactly the same form in my other page and it worked fine.
#model MessagingWebApplication.ViewModel.MessageViewModel
#{ ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Sms</h2>
#using (Html.BeginForm("MessageStatus", "Message"))
{
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.Message.Reciever)
#Html.TextBoxFor(m => m.Message.Reciever, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Reciever)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Sender)
#Html.TextBoxFor(m => m.Message.Sender, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Sender)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Body)
#Html.TextBoxFor(m => m.Message.Body, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Body)
</div>
#Html.HiddenFor(m => m.Message.Id)
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary">Send</button>
}
My model
public class Message
{
[Key]
public int Id { get; set; }
[Required]
public string Sender { get; set; }
[Required]
public string Reciever { get; set; }
[Required]
public string Body { get; set; }
}
Method used for sending
public ActionResult Send(Message message)
{
var viewModel = new MessageViewModel
{
Message = new Message()
};
_context.Add(message);
_context.SaveChanges();
_messageSender.Send(message);
return View("MessageStatus", viewModel);
}
here _context.SaveChanges(); i get SqlException: Cannot insert the value NULL into column 'Id', table 'MyDatabase.dbo.Messages'; column does not allow nulls. INSERT fails.
My issue was that i had failed when updating the database so i just followed this How to delete and recreate from scratch an existing EF Code First database

ASP.NET MVC - Object reference not set to an instance of an object in DropDownList

I have a model Class
public partial class FEES
{
public FEES()
{
}
public long FEE_ID { get; set; }
public decimal AMOUNT { get; set; }
public int CURRENCY_ID { get; set; }
public string NAME { get; set; }
public virtual CURRENCIES CURRENCIES { get; set; }
}
ViewModel
public class FeesViewModel
{
public SelectList CurrenciesList { get; set; }
public FeesViewModelInput input { get; set; }
public class FeesViewModelInput
{
[HiddenInput]
public long FEE_ID { get; set; }
[Display(Name = "Amount")]
[Required(ErrorMessage = "Fee Amount Is Required!")]
[RegularExpression(#"^[0-9,.]+$", ErrorMessage = "Please enter proper currency format e.g. 2,500")]
public decimal AMOUNT { get; set; }
[Display(Name = "Currency")]
[Required(ErrorMessage = "Currency Is Required!")]
public int CURRENCY_ID { get; set; }
[Required(ErrorMessage = "Fee Name Is Required!")]
[Display(Name = "Fee Name")]
public string NAME { get; set; }
}
}
Small service for the ViewModel
public void createFees(FEES fee, FeesViewModel viewModel)
{
fee.FEE_ID = viewModel.input.FEE_ID;
fee.CURRENCY_ID = viewModel.input.CURRENCY_ID;
fee.NAME = viewModel.input.NAME.Trim();
}
I call the service and the ViewModel in my controller.
Controller
public ActionResult Create()
{
FeesViewModel fees = new FeesViewModel();
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
fees.FeeTypesList = new SelectList(_feetypesService.GetFeeTypes().Where(c => c.ACTION_STATUS != 2), "FEE_TYPE_ID", "FEE_TYPE_NAME");
return View();
}
[HttpPost]
public ActionResult Create(FeesViewModel fees)
{
try
{
if (ModelState.IsValid)
{
//check if values is duplicate
if (_feesService.GetFees().Where(c => c.ACTION_STATUS != 2).Any(c => c.NAME.ToLower().Trim() == fees.input.NAME.ToLower().Trim()))
{
this.AddNotification("Fee Name already exist.<br/> Kindly verify the data.", NotificationType.ERROR);
}
else
{
var fee = new BPP.CCSP.Admin.Web.BPPCCSPAdminFeesService.FEES();
var helper = new FeesService();
helper.createFees(fee, fees);
_feesService.AddFee(fee);
var notif = new UINotificationViewModel()
{
notif_message = "Record saved successfully",
notif_type = NotificationType.SUCCESS,
};
TempData["notif"] = notif;
return RedirectToAction("Index");
}
}
}
catch (Exception e)
{
this.AddNotification("Fees cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR);
}
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
return View(fees);
}
And the View
#model BPP.CCSP.Admin.Web.ViewModels.FeesViewModel
#{
//ViewBag.Title = "Create";
}
<div class=" box box-body box-primary">
#using (Html.BeginForm("Create", "Fees", FormMethod.Post, new { #class = "form-horizontal", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, null, new { #class = "text-danger" })
#*#Html.HiddenFor(model => model.faculty_activation_date, new { #Value = System.DateTime.Now })*#
<div class="row .col">
<div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Create Fee</div>
</div>
<div class="panel-body">
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.NAME, "Fee Name")
#Html.TextBoxFor(model => model.input.NAME, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.NAME), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.NAME, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.AMOUNT, "Amount")
#Html.TextBoxFor(model => model.input.AMOUNT, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.AMOUNT), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.AMOUNT, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.CURRENCY_ID, "Currency")
#*#Html.DropDownList("CURRENCY_ID", (IEnumerable<SelectListItem>)ViewBag.name, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })*#
#Html.DropDownListFor(x => x.input.CURRENCY_ID, Model.CurrenciesList, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.CURRENCY_ID, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.FEE_TYPE_ID, "Fee Type")
#Html.DropDownListFor(model => model.input.FEE_TYPE_ID, Model.FeeTypesList, "Please Select a Fee Type", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.FEE_TYPE_ID, null, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="panel-title">
<div class="form-actions no-color">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
}
When I clicked on the View (Create), I got this error
The CurrencyID is a DropDownList coming from CURRENCIES model class.
I have these questions:
Why am I getting this error and how do I resolve it.
How do I do ViewModel without mapping.?
Why am I getting this error and how do I resolve it.
Because the Model is not set in your view. It is null.
When the users visit the Create page, you need to make sure to present them with options in the dropdown. Therefore, you need to make sure you pass the model into the view during GET.
public ActionResult Create()
{
// your code and pass fees to your view.
return View(fees);
}
How do I do ViewModel without mapping. Any example please.
You can use AutoMapper NuGet package to do the mapping.

MVC - Foreign Key Error because of ViewModel?

I am Creating View Model of Employee Class and strongly typed my Create View with the EmployeeViewModel. In future, I will add many classes in my View Model. But the problem is I am getting Gender Foreign Key Error. May be I am binding wrong values in Create Controller. Below is my code:
Create Controllers:
public ActionResult Create()
{
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeeViewModel employeeModel)
{
if (ModelState.IsValid)
{
db.Employees.Add(employeeModel.Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name", employeeModel.Employee.GenderId);
return View(employeeModel);
}
Create View:
#model WebApplication2.EmployeeViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Employee.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.GenderId, "GenderId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GenderId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.GenderId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Models:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public byte GenderId { get; set; }
public Gender Gender { get; set; }
}
public class Gender {
public byte Id { get; set; }
public string Name { get; set; }
}
View Model:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
}

How to do validation from a viewmodel

I have a model with some validations below
public class RequestABook
{
[Required(ErrorMessage = "Name Required")]
[DisplayName("Book Name")]
public string BookName { get; set; }
[Required(ErrorMessage = "Zipcode Required")]
[DisplayName("Zipcode")]
public string ZipCode { get; set; }
[Required(ErrorMessage = "Contact Name Required")]
[DisplayName("Contact Name")]
public string ContactName { get; set; }
[Required(ErrorMessage = "Email Id Required")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required(ErrorMessage = "Book Description Required")]
public string BookDescription { get; set; }
[Required(ErrorMessage = "You need to check one answer")]
public string Answer { get; set; }
}
I have a view model here
public class RequestViewModel
{
public RequestABook MyTestViewModel { get; set; }
}
I have my main page here that loads
#model BookRequestValidation.Models.RequestViewModel
#{
ViewBag.Title = "RequestABook";
}
<h2>RequestABook</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Request Book</legend>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.BookName)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.BookName)
#Html.ValidationMessageFor(m => m.MyTestViewModel.BookName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.ZipCode)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.ZipCode)
#Html.ValidationMessageFor(m => m.MyTestViewModel.ZipCode)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.ContactName)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.ContactName)
#Html.ValidationMessageFor(m => m.MyTestViewModel.ContactName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.Email)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.Email)
#Html.ValidationMessageFor(m => m.MyTestViewModel.Email)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.BookDescription)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.BookDescription)
#Html.ValidationMessageFor(m => m.MyTestViewModel.BookDescription)
</div>
<div id="HCBudget" class="validation">
<label for="budgethealth">Budget Health</label>
#Html.RadioButton("Answer", "Red")
#Html.RadioButton("Answer", "Yellow")
#Html.RadioButton("Answer", "Green")
#Html.ValidationMessageFor(m => m.MyTestViewModel.Answer)
</div>
<input type="submit" value="Request Book" />
</fieldset>
}
Question: How do you guys handle validation with models used in a viewmodel.
Before I used this in a viewmodel everything was working well. By the time I used a viewmodel
validation stopped working.
Here is what the post action looks like.
public ActionResult RequestABook()
{
return View();
}
[HttpPost]
public ActionResult RequestABook(RequestABook quote)
{
return View();
}
It would help greatly if you posted your POST action. However, generally, I can say that validation is only run on related class instances if they are non-null. So, unless a value is posted for at least one of the properties on MyTestViewModel, it will not be instantiated by the modelbinder (MyTestViewModel will be null), and validation on its properties will not be run.
You can fix this scenario by always instantiating the MyTestViewModel property, either via the constructor of your view model or, probably better, using a custom getter and setter:
Constructor
public class RequestViewModel
{
public RequestViewModel()
{
MyTestViewModel = new RequestABook();
}
...
}
Custom Getter and Setter
private RequestABook myTestViewModel;
public RequestABook MyTestViewModel
{
get
{
if (myTestViewModel == null)
{
myTestViewModel = new RequestABook();
}
return myTestViewModel;
}
set { myTestViewModel = value; }
}

asp.net mvc 4 dropdownlist does not return a value

I have 2 models - Question and Category -
public class Question
{
[ScaffoldColumn(false)]
public int QuestionId { get; set; }
[Required]
public string QuestionText { get; set; }
[Required]
public string AnswerA { get; set; }
[Required]
public string AnswerB { get; set; }
[Required]
public string AnswerC { get; set; }
[Required]
public string AnswerD { get; set; }
[Required]
public int Correct { get; set; }
[ForeignKey("Category")]
[Display(Name = "Category")]
[Required]
public int categoryId;
//Navigation property
public virtual Category Category { get; set; }
}
public class Category
{
[ScaffoldColumn(false)]
public int CategoryId { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Question> Question { get; set; }
}
In my QuestionController, I have added code to be able to access the available categories for a dropdownlist in the view -
private void PopulateCategoryDropDownList(object selectedCategory = null)
{
var categoryQuery = from c in db.Categories
orderby c.Name
select c;
ViewBag.categoryId = new SelectList(categoryQuery, "CategoryId", "Name", selectedCategory);
}
And I have the following methods for create -
// GET: /Question/Create
public ActionResult Create()
{
PopulateCategoryDropDownList();
return View();
}
//
// POST: /Question/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Question question)
{
try
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException dex)
{
ModelState.AddModelError("",dex.Message);
}
PopulateCategoryDropDownList(question.Category.CategoryId);
return View(question);
}
My view for creating a new question is as follows -
#model Quiz.Models.Question
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Question</legend>
<div class="editor-label">
#Html.LabelFor(model => model.QuestionText)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.QuestionText)
#Html.ValidationMessageFor(model => model.QuestionText)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AnswerA)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AnswerA)
#Html.ValidationMessageFor(model => model.AnswerA)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AnswerB)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AnswerB)
#Html.ValidationMessageFor(model => model.AnswerB)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AnswerC)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AnswerC)
#Html.ValidationMessageFor(model => model.AnswerC)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AnswerD)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AnswerD)
#Html.ValidationMessageFor(model => model.AnswerD)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Correct)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Correct)
#Html.ValidationMessageFor(model => model.Correct)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.categoryId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.categoryId,(SelectList)ViewBag.categoryId)
#Html.ValidationMessageFor(model => model.categoryId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
So, the issue is that although the question can be created, the categoryId from the dropdownlist is always null.
I have tried a bunch of things, ranging from attempting to access the dropdownlist directly to creating a different viewmodel. However, none of them work as required. Also, my code follows the tutorials available online. I'm not able to figure out what is different.
Please do help me find the mistake in my code.
We might have to narrow things down, I have a feeling something is going wrong with the models being read correctly from ViewBag. Try replacing your Create actions for a moment with the following, where your custom ViewBag filling function has been removed:
public ActionResult Create() {
ViewBag.categoryId = new SelectList(db.Categories, "CategoryId", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Question question) {
try {
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid) {
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
} catch (DataException dex) {
ModelState.AddModelError("",dex.Message);
}
ViewBag.categoryId = new SelectList(db.Categories, "CategoryId", "Name", question.Category.CategoryId);
return View(question);
}
Does this run correctly?
If this doesn't work it must be a model-binding issue. The last thing I can think of trying is change the ViewBag calls to effect the field Category instead of CategoryId. Also update your view when making the DropDownList.