i am trying to generate radio button from model but getting object reference error. i just can not understand where i am making mistake in MVC because i am just learning it. here is my full code. please have a look and tell me where is the mistake. thanks
model class
public class StudentModel
{
[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 = "Sex Required")]
[Display(Name = "Sex :")]
public int SexID { get; set; }
public List<Sex> Sex { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
controller class
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var student = new StudentModel
{
FirstName = "Rion",
LastName = "Gomes",
//I think the best way to populate this list is to call a service here.
Sex = new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
};
return View();
}
[HttpPost]
public ActionResult Index(StudentModel model)
{
if (ModelState.IsValid)
{
//TODO: Save your model and redirect
}
//Call the same service to initialize your model again (cause we didn't post the list of sexs)
return View(model);
}
}
view code
#model MvcRadioButton.Models.StudentModel
#Html.BeginForm()
{
<div>
#Html.LabelFor(model => model.FirstName)
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div>
#Html.LabelFor(model => model.LastName)
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
#{
foreach (var sex in Model.Sex)
{
<div>
#Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID })
#Html.Label("sex" + sex.ID, sex.Type)
</div>
}
}
<input type="submit" value="Submit" />
}
this line throwing error
foreach (var sex in Model.Sex) saying model null or object reference error
You never return a model to your view when the page is initially served. As a result, when you try to iterate over the Sex object you get the null reference error.
[HttpGet]
public ActionResult Index()
{
... code ...
return View(); //The problem is here!
}
You should be returning a model to your view:
[HttpGet]
public ActionResult Index()
{
... code ...
return View(student);
}
Related
public class Encapsulated
{
[Required]
public string CategoryId { get; set; }
}
public class Category
{
public string ID { get; set; }
public string CategoryName { get; set; }
}
public class Test
{
public Encapsulated encapsulated { get; set; }
private IEnumerable<Category> categories;
public IEnumerable<Category> Categories
{
get { return
new List<Category>{new Category{ID="1",CategoryName="abc"}}; }
set { categories = value; }
}
}
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Post" }))
{
#Html.DropDownListFor(
x => x.encapsulated.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
#Html.ValidationMessageFor(x => x.encapsulated.CategoryId)
<input type="submit" value="Submit Form" />
}}
Why doesn't client validation work on dropDownList. If I place
[Required]
public string CategoryId { get; set; }
directly inside my Test class and change the view to
#Html.DropDownListFor( x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"), "-- Please select a category --" ) #Html.ValidationMessageFor(x => x.CategoryId)
client side validation starts working...
I am trying to create an Item that has an ItemType coming from another table. I am unable to get back the actual Type object from the Create page. This is the code I have tried:
Models:
public class ItemType {
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Item> Item{ get; set; }
}
public class Item {
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ItemType ItemType { get; set; }
}
In the ItemController, this is my create code:
public ActionResult Create() {
var itemTypeRepo = new ItemTypeRepository(context);
ViewBag.ItemTypes = new SelectList(itemTypeRepo.GetAll(), "ID", "Name");
return View();
}
[HttpPost]
public ActionResult Create(Item item) {
if (ModelState.IsValid) {
context.Items.Add(item);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(item);
}
In my Create.cshtml view I have tried:
<div class="editor-field">
#Html.DropDownList("ItemType", String.Empty)
#Html.ValidationMessageFor(model => model.ItemType)
</div>
This returns no value at all and throws an error "The value 'X' is invalid." Where X is the ID of the ItemType I selected.
And
<div class="editor-field">
#Html.DropDownListFor(x => x.ItemType.Id, (SelectList)ViewBag.ItemType)
#Html.ValidationMessageFor(model => model.ItemType)
</div>
This creates a stub ItemType object with the correct ID but does not insert it into the database since the object is not fully loaded. If I look at ModelState object, I find that there is an error that the Name field is missing from ItemType object.
I also attempted to solve the problem using the second .cshtml code and adding this code:
public ActionResult Create(Item item) {
item.ItemType = context.ItemTypes.Find(item.ItemType.Id);
if (ModelState.IsValid)
This does not change the value of ModelState.IsValid from false even through it should.
What do I need to do to get this to work?
You should add a property ItemTypeId to your Item entity so that it acts as a foreign key.
public class Item
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int ItemTypeId { get; set; }
[ForeignKey("ItemTypeId")]
public virtual ItemType ItemType { get; set; }
}
You can then use that property for the dropdownlist:
<div class="editor-field">
#Html.DropDownListFor(x => x.ItemTypeId, (SelectList)ViewBag.ItemType)
#Html.ValidationMessageFor(model => model.ItemType)
</div>
I am uploading a file in MVC3 my csHtml page is
<div class="editor-label">
#Html.LabelFor(model => model.Resume)
</div>
<div class="editor-field">
<input type="file" name="Resume" id="Resume" />
#* #Html.EditorFor(model => model.ImageData)*#
#Html.ValidationMessageFor(model => model.Resume)
</div>
My Post Method is
[HttpPost]
public ActionResult SignUp(UserView user)
{
try
{
if (ModelState.IsValid)
{
UserManager userManager = new UserManager();
if (!userManager.IsUserLoginIDExist(user.LoginID))
{
// Request.Params["Resume"];
userManager.Add(user,Request.Files["Resume"]);
FormsAuthentication.SetAuthCookie(user.FirstName, false);
return RedirectToAction("Welcome", "Home");
}
}
}
catch
{
return View(user);
}
return View(user);
}
and my Model is
public class UserView
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Contact Number")]
public string ContactNumber { get; set; }
[Required]
[Display(Name = "Login ID")]
public string LoginID { get; set; }
[Required]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[Display(Name = "Resume")]
public string Resume { get; set; }
}
}
I am getting user.Resume's value as full path(C:\test.png) on some machine and on some machine i am getting just name of the file(test.png). Please help me to deal with this miscellaneous issue
You aren't actually saving the file there at the moment. Perhaps you know this and have left the code out for brevity, but ASP.Net's built-in file handling gives you everything you need.
This question gives you all the info you need: File Upload Asp.net Mvc3.0
How make a dropdownlist? [Edited - almost working code]
View:
<div class="editor-label">
Firma
<div class="editor-field">
#Html.DropDownListFor(x => x.ID_firma, Model.firmaList)
#Html.ValidationMessageFor(model => model.nazwa)
</div>
Model:
public class produktModel
{
[Required(ErrorMessage="Proszę podać nazwę.")]
public string nazwa { get; set; }
[Required(ErrorMessage = "Proszę podać ilść produktu.")]
public decimal ilosc { get; set; }
[Required(ErrorMessage = "Proszę podać jednostkę produktu (np. kg, l, szt.).")]
public string jednostka { get; set; }
[Required(ErrorMessage = "Proszę podać cenę produktu.")]
public decimal cena { get; set; }
public string ID_firma { get; set; }
public IEnumerable<SelectListItem> firmaList { get; set; }
}
Controller:
public ActionResult dodaj()
{
var firma = baza.Firmas;
var model = new produktModel
{
firmaList = firma.AsEnumerable().Select(x => new SelectListItem
{
Value = x.ID_firma.ToString(),
Text = x.nazwa
})
};
return View(model);
}
[HttpPost]
public ActionResult dodaj(produktModel model)
{
Produkt prod = new Produkt();
prod.nazwa = model.nazwa;
prod.ilosc = model.ilosc;
prod.jednostka = model.jednostka;
prod.cena = model.cena;
prod.ID_firma = model.ID_firma;
baza.Produkts.InsertOnSubmit(prod);
baza.SubmitChanges();
return RedirectToAction("zarzadzaj_produktami", "Produkt");
}
It almost work...
I have only one problem (I hope)...
Value is string, and I save his value to database... (I don't now how to write it...)
prod.ID_firma = model.ID_firma;
prod.ID_firma is int. model.ID_firma is this value which is string. So I have an error:
Error 1 Cannot implicitly convert type 'string' to 'int?'
change your model a bit, i have assumed the column names change them according to your code
public class produktModel
{
[Required]
public string name { get; set; }
public decimal price { get; set; }
[Required]
public int companyID {get; set;}
public List<Company> compList {get; set;}
}
public class Company{
public int CompanyID {get;set;}
public string CompanyName {get;set;}
}
ActionResult should look like
public ActionResult add()
{
produktModel model = new produktModel();
model.compList= (from b in base.Companies
select new Company{
CompanyID = b.CompanyID,
CompanyName = b.CompanyName
}).ToList();
return View(model);
}
in your (strongly typed) view
#model produktModel
....
<div class="editor-label">
Company
<div class="editor-field">
#Html.DropDownListFor(model => model.companyID,
new SelectListItem(model.compList,
"CompanyID ",
"CompanyName "))
#Html.ValidationMessageFor(model => model.company_name)
</div>
...
Your question isn't clear enough.
Any way you can use the telerik combox\dropdown list or the default mvc dropdown list. you can find a lot of examples on google for that.
With Telerik write something like this:
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(new SelectList("CompanyID", "CompanyName")))
see this Telerik demo for more information.
I'm trying (without success) to use the Remote validator on a DropDownList:
// Person.cs
public int PersonID { get; set; }
public string Name { get; set; }
// Card.cs
public int CardID { get; set; }
[Remote("PersonValidation", "Validation", ErrorMessage = "...")]
public int PersonID { get; set; }
public virtual Person Person { get; set; }
// CardController
public ActionResult Create()
{
ViewBag.PersonID = new SelectList(db.Persons, "PersonID", "Name");
Card card = new Card();
return View(card);
}
// create.cshtml (Card Views)
<div class="editor-label">#Html.LabelFor(model => model.personID, "Person")</div>
<div class="editor-field">
#Html.DropDownList("PersonID", String.Empty)
#Html.ValidationMessageFor(model => model.PersonID)
</div>
// ValidationController.cs
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public JsonResult PersonValidation(int id)
{
Person person = db.Persons.Find(id);
return Json(person.Cards.Count > 0, JsonRequestBehavior.AllowGet);
}
The PersonValidation is never fired. The others "Remote" validations with text input are working perfectly.
Am I doing something wrong or is there a problem with DropDownList Remote validation?
Thanks!
The validator does not fire because you need to use #Html.DropDownListFor() in order to create an HTML element with "data-val" elements, which will be parsed into unobtrusive validators.