I am getting the following exception:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 34: <div>
Line 35: #Html.LabelFor(m => m.accountStatus)
Line 36: (HERE) #Html.DropDownListFor(m => m.accountStatus, Model.accStat)
Line 37: </div>
Line 38: </fieldset>
Following is the model that I am using.
I have created a List property in my model. And I am referencing it in my Html.DropDownListFor helper.
But I am getting exception.
public class OperatorModel
{
[Required]
[Display(Name = "Account ID")]
public string accountID { get; set; }
[Required]
[Display(Name = "Account Name")]
public string accountName { get; set; }
[Required]
[Display(Name = "Password")]
public string password { get; set; }
public List<SelectListItem> accStat
{
get
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem { Text="ACTIVE", Value="0", Selected=true });
lst.Add(new SelectListItem { Text="DEACTIVATED", Value="1" });
return lst;
}
}
EDIT
Following is my controller code:
public class AdministratorController : Controller
{
//
// GET: /Administrator/
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
public ActionResult Read()
{
return View();
}
public ActionResult Update()
{
return View();
}
public ActionResult Disable()
{
return View();
}
public ActionResult Enable()
{
return View();
}
}
You have to pass the OperatorModel to the view from your action:
for instance:
return View(new OperatorModel());
Related
I have the following model class:
public abstract class CompanyFormViewModelBase
{
public CompanyFormViewModelBase()
{
Role = new CompanyRoleListViewModel();
ContactPerson = new PersonListViewModel();
Sector = new SectorListViewModel();
}
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
public CompanyRoleListViewModel Role { get; set; }
[Display(Name = "Contact Name")]
public PersonListViewModel ContactPerson { get; set; }
public SectorListViewModel Sector { get; set; }
}
public class AddCompanyViewModel : CompanyFormViewModelBase, IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
PlugandabandonEntities db = new PlugandabandonEntities();
CompanyName = CompanyName.Trim();
var results = new List<ValidationResult>();
if (db.Company.Where(p => p.CompanyName.ToLower() == CompanyName.ToLower()).Count() > 0)
results.Add(new ValidationResult("Company already exists.", new string[] { "CompanyName" }));
return results;
}
}
It works fine with "classic" using like:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Plugandabandon.ViewModels.AddCompanyViewModel model)
{
if (ModelState.IsValid)
{
CreateCompany(model);
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
But I want to use this model class for another, ajax form also.
I have the following method:
public JsonResult ReturnJsonAddingCompany(string companyName, int roleID, int sectorID, int personID)
{
Plugandabandon.ViewModels.AddCompanyViewModel model = new ViewModels.AddCompanyViewModel()
{
CompanyName = companyName,
ContactPerson = new ViewModels.PersonListViewModel()
{
SelectedItem = personID
},
Role = new ViewModels.CompanyRoleListViewModel()
{
SelectedItem = roleID
},
Sector = new ViewModels.SectorListViewModel()
{
SelectedItem = sectorID
}
};
ValidateModel(model);
if (ModelState.IsValid)
{
CreateCompany(model);
}
else
{
throw new Exception("Company with such name already exists");
}
var list = Utils.CompanyList();
return Json(list, JsonRequestBehavior.AllowGet);
}
Look at
ValidateModel(model);
line. If model is correct - it works fine. If not correct - it throw exception and break a continue executing of method (and return exception to view). Also, if I set breakpoint on
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
method, it never called in invalid model case! (with valid model Validate method is called). I want to have the behaviour like "classic" method, just validate model and then validate ModelState.IsValid.
Behaviour of ValidateModel(model) is very strange for me, it's a "black box"...
ValidateModel() throws an exception if the model is not valid. Instead, use TryValidateModel()
From the documentation
The TryValidateModel() is like the ValidateModel() method except that the TryValidateModel() method does not throw an InvalidOperationExceptionexception if the model validation fails.
I've tried to follow a few examples from here and a couple other resources to just create a very simple member in my viewmodel and display it as a dropdown list on my view with a dropdownlistfor() helper. I can't seem to wrap my head around it and it's not working with what I'm trying.
here's my viewmodel:
public class Car
{
public int CarId { get; set; }
public string Name { get; set; }
}
public class MyViewModel
{
public IEnumerable<Car> Cars = new List<Car> {
new Car {
CarId = 1,
Name = "Volvo"
},
new Car {
CarId = 2,
Name = "Subaru"
}
};
public int MyCarId { get; set; }
}
and here is my view:
#Html.DropDownListFor(m => m.MyCarId, new SelectList(Model.Cars, "CarId", "Name"))
and here is my controller:
public ActionResult MyView()
{
return View();
}
You need to make sure you send the Model to your View:
public ActionResult Index()
{
var myViewModel = new MyViewModel()
return View(myViewModel);
}
And in your View you need to make sure you're defining your Model:
#model namespace.MyViewModel
You example works fine, I think you forgot to send MyViewModel in POST Action.
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
Hi im using RenderAction helper and during rendering i have this error:
Error executing child request for
handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
Controller code:
public ActionResult GetSearcher()
{
SearcherLines sl = new SearcherLines()
{
RegionList = db.Region.ToList(),
CategoryList = db.Category.ToList(),
SearchValue = null
};
return PartialView(sl);
}
ViewModel
public class SearcherLines
{
public List<Region> RegionList { get; set; }
public List<Category> CategoryList { get; set; }
public string SearchValue { get; set; }
}
partialView
#model IEnumerable<MasterProject.JobForYou.v3.Models.ViewModels.SearcherLines>
#foreach (var i in Model)
{
<p>#i.CategoryList</p><br />
}
Please help.
Try setting OutputCache attribute on controller action
Given I have a Model object like ...
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public DeliveryDetail
{
public string Description { get; set; }
public bool IsSelected { get; set; }
}
and I pass it through to a View like this ...
// Controller
public ActionResult Index()
{
MyModel myModel = Factory.CreateModelWithDeliveryDetails(x);
return View(myModel);
}
How would I render / bind a set of radio buttons (in the view)? Using the following code doesn't post the data back:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => deliveryDetail, false)
}
Selections in a radio button list are mutually exclusive. You can select only a single value. So binding a radio button list to a property of type IEnumerable doesn't make any sense. You probably need to adapt your view model to the requirements of the view (which in your case is displaying a radio button list where only a single selection can be made). Had you used a checkbox list, binding to an IEnumerable property would have made sense as you can check multiple checkboxes.
So let's adapt the view model to this situation:
Model:
public class MyModel
{
public string SelectedDeliveryDetailId { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public class DeliveryDetail
{
public string Description { get; set; }
public int Id { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel
{
DeliveryDetails = new[]
{
new DeliveryDetail { Description = "detail 1", Id = 1 },
new DeliveryDetail { Description = "detail 2", Id = 2 },
new DeliveryDetail { Description = "detail 3", Id = 3 },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Here you will get the id of the selected delivery detail
// in model.SelectedDeliveryDetailId
...
}
}
View:
#model MyModel
#using (Html.BeginForm())
{
foreach (var deliveryDetail in Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDeliveryDetailId, deliveryDetail.Id)
}
<button type="submit">OK</button>
}
You need another property for posted value::
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
public DeliveryDetail SelectedDetail { get; set; }
}
And in view:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDetail, deliveryDetail)
}
In order this to work DeliveryDetail has to be Enum.
I want to pass three field to my controller using RemoteAttribute. How can i do it?
public int ID1 { get; set; }
public int ID2 { get; set; }
[Remote("CheckTopicExists", "Groups", AdditionalFields = "ID1", ErrorMessage = " ")]
public string Topic { get; set; }
public ActionResult CheckTopicExists(string topic, int ID1,int ID2)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
How can i pass three field to that function?
You could separate them by comma:
AdditionalFields = "ID1, ID2"
Full example:
Model:
public class MyViewModel
{
public int ID1 { get; set; }
public int ID2 { get; set; }
[Remote("CheckTopicExists", "Home", AdditionalFields = "ID1, ID2", ErrorMessage = " ")]
public string Topic { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
ID1 = 1,
ID2 = 2,
Topic = "sample topic"
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
public ActionResult CheckTopicExists(MyViewModel model)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
View:
#model MyViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.ID1)
#Html.EditorFor(x => x.ID2)
#Html.LabelFor(x => x.Topic)
#Html.EditorFor(x => x.Topic)
#Html.ValidationMessageFor(x => x.Topic)
<input type="submit" value="OK" />
}
Be aware of sending dates, sometimes controller receive date in a wrong format: was dd/mm/yyyy, receive mm/dd/yyyy
Instead of using
public ActionResult CheckTopicExists(MyViewModel model)
If you use
public ActionResult CheckTopicExists(FormCollection Collection)
then you can reuse the code for other classes as well