How do I bind relational data to a model in ASP.net MVC? - asp.net-mvc-3

I am trying to make an editor for an object in ASP.net MVC 3. It looks something like this:
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.foo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.foo)
#Html.ValidationMessageFor(model => model.foo)
</div>
#if (Model.Items.Count > 0)
{
<table>
#foreach (var ii in Model.Items)
{ #Html.EditorFor(item => ii) }
</table>
}
In this example, Items is a list of another kind of object. The problem is, when the model is posted back from being edited in the view, the data changes to Model.Items aren't there, while the data changes to Name and foo work. How can I make it so that the data for Items binds correctly?

Model class:
public class HomeControllerModel
{
public string Name { get; set; }
public string foo { get; set; }
public List<string> Items { get; set; }
public HomeControllerModel()
{
Items = new List<string>();
}
}
Controller class:
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var model = new HomeControllerModel();
model.Name = "LukLed";
model.foo = "bar";
model.Items.Add("AAA");
model.Items.Add("BBB");
model.Items.Add("CCC");
return View(model);
}
[HttpPost]
public ActionResult Index(HomeControllerModel model)
{
return View(model);
}
View:
#using MvcApplication4.Controllers
#model HomeControllerModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
<form action="/Home/Index" method="post">
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.foo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.foo)
#Html.ValidationMessageFor(model => model.foo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Items)
</div>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
You don't have to iterate through Items.

Related

Page to create object and sub object

I'm sure there have been tons of people asking this type of question but I can't quite figure out how to word it.
I will try to explain. I am working to model an ethernet network where devices have ip addresses. I've setup my entity framework models so that the ip and subnet are stored in a separate table to ensure uniqueness across the system.
I'd like the user to be able to create a device and its associated IP at the same time if the IP they want is not already in a dropdown list.
I setip a partial of the IP Address page RenderPartial on the device page and I get this error:
Here is the question, How do I fix this error:
The model item passed into the dictionary is of type PcnWeb.Models.Device, but this dictionary requires a model item of type PcnWeb.Models.IPAddress.
Here are my models:
IP Address Model:
namespace PcnWeb.Models
{
public class IPAddress
{
public virtual ICollection<Device> Devices { get; set; }
[Key]
public int ipAddressRecId { get; set; }
public Nullable<int> ipOctet1 { get; set; }
public Nullable<int> ipOctet2 { get; set; }
public Nullable<int> ipOctet3 { get; set; }
public Nullable<int> ipOctet4 { get; set; }
public Nullable<int> smOctet1 { get; set; }
public Nullable<int> smOctet2 { get; set; }
public Nullable<int> smOctet3 { get; set; }
public Nullable<int> smOctet4 { get; set; }
}
}
And the Device Model:
namespace PcnWeb.Models
{
public class Device
{
[Key]
public int deviceRecId { get; set; }
public int ipAddressRecId { get; set; }
[Required, StringLength(64)]
[Unique]
public string Name { get; set; }
[StringLength(256)]
public string Comment { get; set; }
public virtual IPAddress IPAddress { get; set; }
}
}
I would have thought that it would be pretty easy to have the associated device creation page with an inline ipaddress creation page.
Here's the Device page:
#model PcnWeb.Models.Device
#{
ViewBag.Title = "Create a Device";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Device</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ipAddressRecId, "IPAddress")
</div>
<div class="editor-field">
#Html.DropDownList("ipAddressRecId", String.Empty)
#Html.ValidationMessageFor(model => model.ipAddressRecId)
</div>
#{
Html.RenderPartial("~/Views/IP_Address/_Create.cshtml");
}
<div class="editor-label">
#Html.LabelFor(model => model.Name, "Name")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Comment, "Comment")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Comment)
#Html.ValidationMessageFor(model => model.Comment)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Here is the IP Address Partial:
EDIT: Sorry I forgot to include this
#model PcnWeb.Models.IPAddress
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>IPAddress</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ipOctet1, "ipOctet1")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ipOctet1)
#Html.ValidationMessageFor(model => model.ipOctet1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ipOctet2, "ipOctet2")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ipOctet2)
#Html.ValidationMessageFor(model => model.ipOctet2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ipOctet3, "ipOctet3")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ipOctet3)
#Html.ValidationMessageFor(model => model.ipOctet3)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ipOctet4, "ipOctet4")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ipOctet4)
#Html.ValidationMessageFor(model => model.ipOctet4)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.smOctet1, "smOctet1")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.smOctet1)
#Html.ValidationMessageFor(model => model.smOctet1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.smOctet2, "smOctet2")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.smOctet2)
#Html.ValidationMessageFor(model => model.smOctet2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.smOctet3, "smOctet3")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.smOctet3)
#Html.ValidationMessageFor(model => model.smOctet3)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.smOctet4, "smOctet4")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.smOctet4)
#Html.ValidationMessageFor(model => model.smOctet4)
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
So from all this, it looks great to me, the validation works client side. I'll have to write some javascript to hide the IP address partial unless they select new from the dropdown list.
Here is the question again, How do I fix this error:
The model item passed into the dictionary is of type PcnWeb.Models.Device, but this dictionary requires a model item of type PcnWeb.Models.IPAddress.
This errors means that there is mismatch between model type in your partial view and type of model passed to this view. But as i can see you trying to render the partial view without model passing.
Your code example worked for me.
So, to solve this problem you can do the next steps.
Ensure that the view path is right;).
Try so 'send' model to your partial view explicity like
main view
#model PcnWeb.Models.Device
//some code here
#Html.Partial("path_to_view", Model)
partial view.
#model PcnWeb.Models.Device
#Html.DropdownListFor(x=>x.ipAddressRecId, YourDlistSource) //or anything you need
this works for me.
Alternatively if you need edit submodel in partial view you can do this
#model PcnWeb.Models.Device
//some code here
#Html.Partial("path_to_view", Model.IPAddress)//pass the submodel to partial view
then your partial view must be with another type.
#model PcnWeb.Models.IPAddress
//some code here
Answer on comment. To resolve object reference exception try initialize your submodel in constructor.
public class Device
{
///properties
public Device()
{
IPAddress = new IPAddress();
}
}

Display message using view bag without refreshing view

I have a view A From ControllerA Which has two buttons 1. Create 2. Update
Upon clicking update or Create its opening a new partial viewB As popup from another controller B.
What iam trying to get is If a record is created successfully in b I am now closing the popup. Apart from closing the popup I want to display a message in view A.
I am trying like this:
Controller B
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
try
{
UpdateModel(res);
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
}
return View(res);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(res);
}
}
And in the view A:
#if(ViewBag.Message!=null)
{
#ViewBag.Message
}
View B:
#model DreamTrade.Web.BL.ViewModels.ProjectViewModelNew
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout_Popup.cshtml";
}
#if (ViewBag.RecordAdded != null && (bool)ViewBag.RecordAdded)
{
<script type="text/javascript">
parent.$.nmTop().close();
$('#jqgprojectnew').text("Record added successfully");//jqgprojectnew is the name of grid in view A
</script>
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Project</legend>
#Html.HiddenFor(model => model.ProjectID)
<div class="editor-label">
#Html.LabelFor(model => model.ProjectDetail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectDetail)
#Html.ValidationMessageFor(model => model.ProjectDetail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProjectRef)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectRef)
#Html.ValidationMessageFor(model => model.ProjectRef)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProjectName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectName)
#Html.ValidationMessageFor(model => model.ProjectName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StatusList)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ProjectStatusId,new SelectList(Model.StatusList,"SourceStatusId","Description"),"Please Select")
#Html.ValidationMessageFor(model => model.ProjectStatusId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CustomerList)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Id,new SelectList(Model.CustomerList,"Id","Name"),"Please Select")
#Html.ValidationMessageFor(model => model.Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<div>
Back to list
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
please let me know where iam doing wrong
Include a label field where you want to show the message.
<label id=mylabel></label>// Add this before jqgrid
Modify the code to:
#if (ViewBag.RecordAdded != null && (bool)ViewBag.RecordAdded)
{
<script type="text/javascript">
parent.$.nmTop().close();
$('#mylabel').text("Record added successfully");
</script>
}

Selected item list and other object

I'm new in asp.net mvc3 programming and I'm trying to build a specific form. I need to have a form with the user field (which I have) but also a list of object (in that case SStatus).
My form :
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Création d'utilisateur</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Lastname)
#Html.ValidationMessageFor(model => model.Lastname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Firstname)
#Html.ValidationMessageFor(model => model.Firstname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Login)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Login)
#Html.ValidationMessageFor(model => model.Login)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<p>Status</p>
#{
//The error was form here
#{
var list = ViewBag.listStatus as List<SStatus>;
}
#if (list != null)
{
foreach(var status in list)
{
<option value=#status.ID>#status.Name</option>
}
}
</select>
}
<p>
<input type="submit" value="Création" />
</p>
</fieldset>
}
The list call :
public ActionResult CreateUserView()
{
RestClient client = new RestClient(Resource.Resource.LocalUrlService);
RestRequest request = new RestRequest("/status/all", Method.GET);
var response = client.Execute(request);
if(response.StatusCode == HttpStatusCode.OK)
{
List<SStatus> listSatus = JsonHelper.FromJson<List<SStatus>>(response.Content);
ViewBag.listStatus = listSatus;
}
return View();
}
And the form post:
[HttpPost]
public ActionResult CreateUserView(Uuser userToCreate, string list)
{
//list got the ID of SStatus.
if (ModelState.IsValid)
{//Stuff}
}
So the question is : How get the selected list item ?
Regards.
Use a view model pattern. I still don't see how your Uuser object is sent to the view (via the default [HttpGet] action, but I think I see what you're trying to accomplish.) If you refactor this way, you'll still get to use the built-in validation, automagic model binding, etc.
public class CreateUserViewModel
{
public Uuser User { get; set; }
public string Status { get; set; }
}
Then your action parameter should be of type CreateUserViewModel e.g.
[HttpPost]
public ActionResult CreateUserView(CreateUserViewModel vm)
{
if(ModelState.IsValid)
{
{//Stuff}
}
I believe you'll need a name attribute on the <select> element in order for it to be posted.
<p>Status</p>
#{
<select name="Status">
Although, you're going to run into trouble if the model isn't valid. Your view should be strongly typed against CreateUserViewModel e.g.
#model YourModelNamespace.CreateUserViewModel
So, your Lastname property might look like this (note the .User)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Création d'utilisateur</legend>
<div class="editor-label">
#Html.LabelFor(model => model.User.Lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User.Lastname)
#Html.ValidationMessageFor(model => model.User.Lastname)
</div>
And finally, I guess you could keep the possible list of status in the ViewBag, but you'll want to set the selected value to #Model.Status. You may want to consider changing CreateUserViewModel.Status to a List<SelectListItem> that you can populate from your controller e.g. your GET action should return View(CreateUserViewModel)
public ActionResult CreateUserViewModel()
{
CreateUserViewModel vm = new CreateUserViewModel();
vm.User = // set user
vm.Status = new List<SelectListItem>()
{
new SelectListItem()
{
Value = "status1",
Text = "status 1",
Selected = false
},
new SelectListItem()
{
Value = "status2",
Text = "status 2",
Selected = true
},
};
return View(vm); // this is the correct way to strongly type your view
}

Partialview not returning model for a sortedlist

I am very, very new to MVC, so please bear with my question, I have to work with the following structure.
I have the following models, Facility and Address. Facility contains a SortedList of Address, I have reduced the number of properties for clarity,
public class AppFacility
{
public AppFacility()
{
this.Addresses = new SortedList<string, AppAddress>();
}
public SortedList<string, AppAddress> Addresses { get; set; }
[DisplayNameAttribute("Facility ID")]
public int FacilityID { get; set; }
[Required(ErrorMessage = "Facility Name is a required field")]
[DisplayNameAttribute("Facility Name")]
public string FacilityName { get; set; }
[DisplayNameAttribute("Doing Business As")]
public string Dba { get; set; }
[DisplayNameAttribute("Nbr. Of Employees")]
public int NbrOfEmployees { get; set; }
}
public class AppAddress
{
[DisplayNameAttribute("City")]
public string City { get; set; }
[DisplayNameAttribute("State")]
public string State { get; set; }
[DisplayNameAttribute("Street Name")]
public string StreetName { get; set; }
}
Controller:
[HttpPost]
public ActionResult FacilityCreate(AppFacility objFacility)
{
facilityManager = new Manager.AppFacilityManager();
if (facilityManager.InsertAppFacility(objFacility))
{
return RedirectToAction("FacilityInfo", new { id = objFacility.FacilityID });
}
return View((AppFacility)Session["FacilityObject"]);
}
View:
FacilityCreate
#model Model.CORE.BO.AppFacility
<table width="100%" align="center" border="0" class="SectionTables">
<tr>
<td class="SubtitleHeader">
Facility
</td>
</tr>
<tr>
<td class="SubtitleHeader1">
Enter Facility Information
</td>
</tr>
<tr>
<td align="center">
#Html.Partial(p_CreateEditAppFacility, Model)
</td>
</tr>
Partial view:
p_CreateEditAppFacility:
This contains the p_CreateEditAddress partial view as well.
#model Model.CORE.BO.AppFacility
#using (Html.BeginForm("FacilityCreate", "Form", FormMethod.Post,
new { id = "saveForm", name = "saveForm" }))
{
#Html.ValidationSummary(true)
<div class="main">
<fieldset>
<legend>Operator Information</legend>
<div class="editor-label">
#Html.Label("Facility Name (Business Name of Operator to Appear): ")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FacilityName)
#Html.ValidationMessageFor(model => model.FacilityName)
</div>
<div class="editor-label">
#Html.Label("Owner's Business Name (If different from Business Name of Operator): ")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dba)
#Html.ValidationMessageFor(model => model.Dba)
</div>
<div class="editor-label">
#Html.Label("No of Employees:")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.NbrOfEmployees)
#Html.ValidationMessageFor(model => model.NbrOfEmployees)
</div>
</fieldset>
<fieldset>
<legend>Address Information</legend>
#{
int i = 0;
foreach (KeyValuePair<string, Model.CORE.BO.AppAddress> addressRow in Model.Addresses)
{
<div class="editor-field">
#Html.Partial(p_CreateEditAddress, addressRow.Value, new ViewDataDictionary(Html.ViewDataContainer.ViewData) { TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = string.Format("objFacility.Addresses[{0}]", i) } })
</div>
i++;
}
}
</fieldset>
<p>
<input id="SaveFacility" name="SaveInfo" type="submit" value="Save Information" />
</p>
</div>
}
PartialView:
p_CreateEditAddress
#model Model.CORE.BO.AppAddress
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.StreetName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StreetName)
#Html.ValidationMessageFor(model => model.StreetName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.State)
#Html.ValidationMessageFor(model => model.State)
</div>
My question is that in the Controller the objFacility.Addresses does not get the values entered for the model AppAddress, it is always null. The AppFacility gets populated though.
The html behind looks like this for p_CreateEditAddress
<div class="editor-field">
<input class="text-box single-line"
id="objFacility_Addresses_0__StreetName"
name="objFacility.Addresses[0].StreetName" type="text" value="" />
<span class="field-validation-valid"
data-valmsg-for="objFacility.Addresses[0].StreetName" data-valmsg-replace="true"></span>
</div>
Please help.
You just need to change your Partial View call to take the correct prefix. You don't give it the Model name as the default model binder will be creating an instance of your class and looking for fields that match the names of the items in the Request.Form collection. It knows nothing about the variable name you've gave your model, just the properties of your Model's class.
Try this (I put line breaks in for readability):
#Html.Partial(p_CreateEditAddress, addressRow.Value,
new ViewDataDictionary(Html.ViewDataContainer.ViewData) {
TemplateInfo = new System.Web.Mvc.TemplateInfo {
HtmlFieldPrefix = string.Format("Addresses[{0}]", i)
}
})
I guess the generated HTML is not proper for model binding.
It should not be objFacility.Addresses[0].StreetName but Addresses[0].StreetName.

Required data annotation is not working on a DropDownlist inside my asp.net mvc3

i have defined the following in my validation model class
public class Visit_Validation
{
[Display(Name = "Assign to Doctor")]
[Required(ErrorMessage= "Please select a Doctor")]
public string DoctorID { get; set; }}
Then i have created the DoctorID Selectlist as follow:-
public ActionResult Create(int patientid)
{
Visit visit = new Visit();
var allusers = Membership.GetAllUsers();
ViewBag.DoctorID = new SelectList(allusers, "Username", "Username");
return View(visit);
}
and finally i define the dropdownlist at the view as follow:-
<div class="editor-label">
#Html.LabelFor(model => model.DoctorID)
</div>
<div class="editor-field">
#Html.DropDownList("DoctorID", String.Empty)
#Html.ValidationMessageFor(model => model.DoctorID)
</div>
but the problem i am facing is that incase the user leave the DoctorID dropdownlist empty then the [Required(ErrorMessage= "Please select a Doctor")] error will not be displayed? so what might be going wrong?
BR
Update:-
here is the full view code:-
<h2>Create</h2>
#section scripts{
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Visit</legend>
<div class="editor-label">
#Html.LabelFor(model => model.VisitTypeID, "VisitType")
</div>
<div class="editor-field">
#Html.DropDownList("VisitTypeID", String.Empty)
#Html.ValidationMessageFor(model => model.VisitTypeID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Date)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Date, new { value = "FL", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Date)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Note)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Note)
#Html.ValidationMessageFor(model => model.Note)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DoctorID)
</div>
<div class="editor-field">
#Html.DropDownList("DoctorID", String.Empty)
#Html.ValidationMessageFor(model => model.DoctorID)
</div>
<div class="editor-label">
Visit Status
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.VisitStatu.Description, new { value = "FL", disabled = "disabled" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CreatedBy)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.CreatedBy, new { value = "FL", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.CreatedBy)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
here is the Post action method code:-
[HttpPost]
public ActionResult Create(Visit visit)
{
if (ModelState.IsValid)
{
visit.StatusID = repository.GetVisitStatusByDescription("Assinged");
visit.CreatedBy = User.Identity.Name;
visit.Date = DateTime.Now;
repository.AddVisit(visit);
repository.Save();
return RedirectToAction("Index");
}
ViewBag.DoctorID = new SelectList(Membership.GetAllUsers(), "Username", "Username");
ViewBag.StatusID = new SelectList(repository.FindAllVisitStatus(), "StatusID", "Description");
ViewBag.VisitTypeID = new SelectList(repository.FindAllVisitType(), "VisitTypeID", "Description");
return View(visit);
}
In order for validation to be triggered you need to have your POST controller action take the model as parameter:
[HttpPost]
public ActionResult Create(Visit visit)
{
...
}
or use the TryUpdateModel method:
[HttpPost]
public ActionResult Create()
{
Visit visit = new Visit();
if (!TryUpdateModel(visit))
{
// validation failed
}
...
}
When the form is submitted to this controller action the default model binder will invoke the validation rules contained in this Visit model. If your controller action never works with this model there's nothing out there that will ever interpret the data annotations that you put on it.

Resources