Server Error in '/' Application.
The model item passed into the dictionary is of type 'Develosoft4.Models.Cita', but this dictionary requires a model item of type 'Develosoft4.Models.CitaFormViewModel'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'Develosoft4.Models.Cita', but this dictionary requires a model item of type 'Develosoft4.Models.CitaFormViewModel'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
This is the Create.aspx that throws the error:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Develosoft4.Models.CitaFormViewModel>" %>
<h2>Create</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend></legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Cita.materia)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Cita.materia, Model.Materias)%>
<%: Html.ValidationMessageFor(model => model.Cita.materia)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Cita.cubiculo)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Cita.cubiculo, Model.Cubiculos)%>
<%: Html.ValidationMessageFor(model => model.Cita.cubiculo)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Cita.profesor)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Cita.profesor, Model.Profesores)%>
<%: Html.ValidationMessageFor(model => model.Cita.profesor)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Cita.fecha)%>
</div>
<div class="editor-field">
<%: Html.ValidationMessageFor(model => model.Cita.fecha)%>
<form>
<input type="text" name="fecha" id="campofecha">
</form>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Cita.horaInicio)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Cita.horaInicio)%>
<%: Html.ValidationMessageFor(model => model.Cita.horaInicio)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Cita.horaFinal)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Cita.horaFinal)%>
<%: Html.ValidationMessageFor(model => model.Cita.horaFinal)%>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
This is CitaFormViewModel.cs
using System.Web.Mvc;
namespace Develosoft4.Models
{
public class CitaFormViewModel
{
private static CubiculoRepository cubiculosRepository = new CubiculoRepository();
private static MateriaRepository materiasRepository = new MateriaRepository();
private static ProfesorRepository profesorRepository = new ProfesorRepository();
// Properties
public Cita Cita { get; private set; }
public SelectList Cubiculos { get; private set; }
public SelectList Materias { get; private set; }
public SelectList Profesores { get; private set; }
// Constructor
public CitaFormViewModel(Cita cita)
{
Cita = cita;
Cubiculos = new SelectList(cubiculosRepository.FindAllCubiculos(),"id","nombre", cita.cubiculo);
Materias = new SelectList(materiasRepository.FindAllMaterias(), "id", "nombre", cita.materia);
Profesores = new SelectList(profesorRepository.FindAllProfesores(), "id", "nombre", cita.profesor);
}
}
}
CitaController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Develosoft4.Models;
namespace Develosoft4.Controllers
{
public class CitaController : Controller
{
CitaRepository repository = new CitaRepository();
//
// GET: /Cita/
[Authorize (Roles= "director")]
public ActionResult Index(int page = 0)
{
const int pageSize = 10;
var citas = repository.FindAllCitas();
var paginatedCita = new PaginatedList<Cita>(citas,page,pageSize);
return View(paginatedCita);
}
//
// GET: /Cita/Details/2
public ActionResult Details(int id)
{
Cita cita = repository.GetCita(id);
if (cita == null)
return View("NotFound");
else
return View("Details", cita);
}
//
// GET: /Cita/Edit/2
public ActionResult Edit(int id)
{
Cita cita = repository.GetCita(id);
CitaFormViewModel viewModel = new CitaFormViewModel(cita);
return View(viewModel);
}
//
// POST: /Cita/Edit/2
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
Cita cita = repository.GetCita(id);
try
{
UpdateModel(cita);
repository.Save();
return RedirectToAction("Details", new { id = cita.id });
}
catch
{
//ModelState.AddRuleViolations(materia.GetRuleViolations());
return View(cita);
}
}
//
// GET: /Cita/Create
public ActionResult Create()
{
Cita cita = new Cita();
return View( new CitaFormViewModel( cita));
}
//
// POST: /Cita/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Cita cita)
{
if (ModelState.IsValid)
{
try
{
repository.Add(cita);
repository.Save();
return RedirectToAction("Details", new { id = cita.id });
}
catch
{
//ModelState.AddRuleViolations(materia.GetRuleViolations());
}
}
return View(cita);
}
//
// HTTP GET: /Cita/Delete/1
public ActionResult Delete(int id)
{
Cita cita = repository.GetCita(id);
if (cita == null)
return View("NotFound");
else
return View();
}
// actitud
// HTTP POST: /Cita/Delete/1
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, string confirmButton)
{
Cita cita = repository.GetCita(id);
if (cita == null)
return View("NotFound");
repository.Delete(cita);
repository.Save();
return View("Deleted");
}
}
}
Your trying to pass your model an object of type Develosoft4.Models.Cita when it is expecting an object of type Develosoft4.Models.CitaFormViewModel.
You probably have a strongly typed view so you need to pass it the type it is expecting.
Check your controller when you should have something like this at the end:
return View(new Develosoft4.Models.CitaFormViewModel()
{
// initializers
});
No idea what you code actually looks like so this is stab in the dark :)
EDIT: Based on the code you added, it looks like your Post version of Create is returning the wrong type to the view.
You are doing this:
return View(cita);
When your Create view is expecting a CitaFormViewModel so you should probably be doing:
return View(new CitaFormViewModel(cita));
Just lke you did in the Get version of the Create view.
The model item passed into the dictionary is of type 'Develosoft4.Models.Cita', but this dictionary requires a model item of type 'Develosoft4.Models.CitaFormViewModel'
It looks like you are returning the wrong model type from an action method.
//This is where I think the error is. It is expecting a CityFormViewModel instead of a Cita object
return View(citaModel);
Related
How can I create a form in ASP.NET MVC2, send the data to a controller that adds something to the database and then redirects to the home page? Can you give me an example/snippet of how it's done in the View?
For some reason, I have a bug in my form. Here's the code:
AddEvent.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Add Event</h2>
<% using (Html.BeginForm()) { %>
<div>
<%= Html.LabelFor(x => x.EventName) %>:
<%= Html.TextBoxFor(x => x.EventName) %>
</div>
<div>
<%= Html.LabelFor(x => x.EventDate) %>:
<%= Html.TextBoxFor(x => x.EventDate) %>
</div>
<div>
<%= Html.LabelFor(x => x.EventLocation) %>:
<%= Html.TextBoxFor(x => x.EventLocation) %>
</div>
<div>
<%= Html.LabelFor(x => x.EventDescription) %>: </br>
<%= Html.TextAreaFor(x => x.EventDescription) %>
</div>
<input type="submit" value="Submit" />
<% } %>
HomeController.cs
public ActionResult AddEvent()
{
return View();
}
[HttpPost]
public ActionResult AddEvent(Event e)
{
e.EventCreatorName = Session["UserName"].ToString();
DatabaseModels db = new DatabaseModels();
db.AddEvent(e);
return RedirectToAction("Index", "Home");
}
DatabaseModels.cs
public bool AddEvent(Event e)
{
anEvent eventToAdd = new anEvent();
eventToAdd.creator_nickname = e.EventCreatorName;
eventToAdd.event_category = 1; // TODO
if (e.EventDate == null)
{
eventToAdd.event_date = new DateTime();
}
else
{
eventToAdd.event_date = DateTime.Parse(e.EventDate);
}
eventToAdd.event_location = e.EventLocation;
eventToAdd.event_name = e.EventName;
m_db.AddToevents(eventToAdd);
m_db.SaveChanges();
return true;
}
I type in details in the form and I get the following Exception:
This property cannot be set to a null value.
on event_location. Can anyone help solve this?
The asp.net/mvc site contains numerous examples, videos and tutorials about MVC that are worth reading. Here's an example of how the scenario you are asking about could be implemented:
Model:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Controller:
public class PersonsController: Controller
{
public ActionResult Index()
{
return View(new Person());
}
[HttpPost]
public ActionResult Index(Person person)
{
// The person object here will have it's FirstName
// and LastName properties bound to whatever values
// the user entered in the corresponding textboxes in the form
// TODO: save person to database
// redirect to /home/index
return RedirectToAction("index", "home");
}
}
View:
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.Person>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<div>
<%= Html.LabelFor(x => x.FirstName) %>:
<%= Html.TextBoxFor(x => x.FirstName) %>
</div>
<div>
<%= Html.LabelFor(x => x.LastName) %>:
<%= Html.TextBoxFor(x => x.LastName) %>
</div>
<input type="submit" value="Save" />
<% } %>
</asp:Content>
Now you might be wondering about the TODO part. Usually I create a repository to decouple my data access logic from my controller:
public interface IPersonsRepository
{
void Save(Person person);
}
and then use constructor injection of this repository into my controller:
public class PersonsController: Controller
{
private readonly IPersonsRepository _repository;
public PersonsController(IPersonsRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(new Person());
}
[HttpPost]
public ActionResult Index(Person person)
{
// The person object here will have it's FirstName
// and LastName properties bound to whatever values
// the user entered in the corresponding textboxes in the form
// save person to database
_repository.Save(person);
// redirect to /home/index
return RedirectToAction("index", "home");
}
}
Obviously now the last part that's left is the implementation of this repository. This will depend on how/where your data is stored and the particular data access technology you would be using. So are you using a relational database, flat text file, XML file, object database, some database stored on the cloud, ... how are you going to access it: EF, NHibernate, Linq-to-XML, some REST API, ...
Once you make your choice you simply implement the interface and instruct your DI framework to pass the proper implementation to the controller constructor.
I am trying to validate a viewmodel using fluent validation. When i post the viewmodel object, the modelstate.isvalid always returns false. When i have checked the values on the posted object, the properties which were used to get the data to be shown in dropdowns are also being validated. How to resolve this. Am i doing it in a wrong way, pls help.
I'm new to ASP.net MVC and just trying out using fluent validation and fluent NHibernate mappings in this project.
More details as follows:
I have a domain model object as below:
[Validator(typeof(TestRequirementValidator))]
public class TestRequirement
{
public virtual int Id { get; private set; }
public virtual int SampleId { get; set; }
public virtual int TestId { get; set; }
public virtual int StandardId { get; set; }
public virtual string Description { get; set; }
public virtual Sample Sample { get; set; }
public virtual Test Test { get; set; }
public virtual Standard Standard { get; set; }
}
I have created a view model as below:
[Validator(typeof(TestRequirementViewModelValidator))]
public class TestRequirementViewModel
{
public TestRequirement TestRequirement;
public SelectList Samples;
public SelectList Tests;
public SelectList Standards;
public TestRequirementViewModel()
{
ISession _session = FNHsessionFactory.GetSessionFactory();
this.TestRequirement = new TestRequirement();
this.Samples = new SelectList(from S in _session.Linq<Sample>() select S, "Id", "Name");
this.Tests = new SelectList(from T in _session.Linq<Test>() select T, "Id", "Name");
this.Standards = new SelectList(from St in _session.Linq<Standard>() select St, "Id", "Name");
}
}
Model Validator is as below:
public class TestRequirementValidator : AbstractValidator<TestRequirement>
{
public TestRequirementValidator()
{
RuleFor(x => x.SampleId)
.NotEmpty()
.WithMessage("This field is required")
.DisplayName("Sample Name");
RuleFor(x => x.TestId)
.DisplayName("Test Name");
RuleFor(x => x.StandardId)
.NotEmpty()
.WithMessage("This field is required")
.DisplayName("Standard Name");
RuleFor(x => x.Description)
.NotEmpty()
.WithMessage("This field is required")
.Length(0, 10)
.WithMessage("Length of this field cannot be more than 10 characters");
}
}
View model validator is as below:
public class TestRequirementViewModelValidator:AbstractValidator-TestRequirementViewModel-
{
public TestRequirementViewModelValidator()
{
RuleFor(x => x.TestRequirement)
.SetValidator(new TestRequirementValidator());
}
}
View is as below:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<foo.Models.ViewModels.TestRequirementViewModel>" MasterPageFile="~/Views/shared/site.master" %>
<asp:Content ContentPlaceHolderID="MainContent" ID="MainContentContent" runat="server">
<h3><%= Html.Encode(ViewData["Message"]) %></h3>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Create Test Requirement</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.TestRequirement.SampleId) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.TestRequirement.SampleId, new SelectList(Model.Samples.Items, Model.Samples.DataValueField, Model.Samples.DataTextField), "Select Sample") %>
<%= Html.ValidationMessageFor(model => model.TestRequirement.SampleId) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.TestRequirement.TestId) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.TestRequirement.TestId, new SelectList(Model.Tests.Items, Model.Tests.DataValueField, Model.Tests.DataTextField), "Select Test") %>
<%= Html.ValidationMessageFor(model => model.TestRequirement.TestId) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.TestRequirement.StandardId) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.TestRequirement.StandardId, new SelectList(Model.Standards.Items, Model.Standards.DataValueField, Model.Standards.DataTextField), "Select Standard") %>
<%= Html.ValidationMessageFor(model => model.TestRequirement.StandardId) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.TestRequirement.Description) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.TestRequirement.Description) %>
<%= Html.ValidationMessageFor(model => model.TestRequirement.Description) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<%= Html.ClientSideValidation<TestRequirement>("TestRequirement") %>
</asp:Content>
Controller is as below:
public ActionResult TestRequirement()
{
TestRequirementViewModel NewTestRequirement = new TestRequirementViewModel();
return View(NewTestRequirement);
}
[HttpPost]
public ActionResult TestRequirement(TestRequirementViewModel NewTestRequirement)
{
if(ModelState.IsValid)
{
ISession _session = FNHsessionFactory.GetSessionFactory();
_session.SaveOrUpdate(NewTestRequirement.TestRequirement);
ViewData["Message"] = "New Test Requirement has been created successfully";
return View();
}
return View(NewTestRequirement);
}
I can't help with Fluent Validation, but as you've tagged this as fluent-nhibernate I thought I should comment on your NHibernate usage.
Your view model should not be using NHibernate in its constructor; in fact, your view model should just be a data structure that gets populated by an external service. Similarly, you might want to do the same with your controller; it's common for people to extract data access into a repository to isolate their controllers (and make testing easier, you are testing aren't you?).
If you're using a repository, you can then project your view model from your entity; you can do that either by using NHibernate projections and transformers or by using a tool like AutoMapper.
I gotta the following code in controller and view. The problem is that the model(Photo is an Entity Framework entity) is empty(all fields are nulled). Why?
// GET: /Admin/Photo/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Admin/Photo/Create
[HttpPost]
public ActionResult Create(int id, FormCollection collection)
{
try
{
var file = (HttpPostedFileBase) Request.Files[0];
if (file != null && file.FileName != null)
{
var filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Photos/Product/", Path.GetFileName(file.FileName));
file.SaveAs(filename);
var photo = new Photo();
photo.Description = collection["Description"];
photo.Main = collection["Main"].Contains("true");
photo.Filename = Path.GetFileName(file.FileName);
photo.Product_Id = id;
Entities.AddToPhotos(photo);
Entities.SaveChanges();
}
else
{
ModelState.AddModelError("", "Plik musi zostać załadowany.");
return View();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
<h2>Create</h2>
<% using (Html.BeginForm(null, null, null, FormMethod.Post, new {enctype = "multipart/form-data" })) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Description) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Description) %>
<%: Html.ValidationMessageFor(model => model.Description) %>
</div>
<div class="editor-label">
<label for="MainContent_file">Plik: </label>
</div>
<div class="editor-field">
<asp:FileUpload ID="file" runat="server" />
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Main) %>
</div>
<div class="editor-field">
<%: Html.CheckBoxFor(model => model.Main) %>
<%: Html.ValidationMessageFor(model => model.Main) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
Update: I checked and the collection is populated with proper fields, but they are all nulled.
Check to make sure that the name attributes in the resulting html match your collection name. You could also change your public ActionResult Create(int id, FormCollection collection) to public ActionResult Create(int id, YourViewModel model) to automagically map the post values to the model.
Check the html source in the browser.
It might be sending them as: "Photo.Description"
I am learning asp.net mvc 2 and fluent validation. My setup is shown after the text here. My problem is that I do not know how to set the errors contained in the res object on the view page in a nice way. How should this be done? As it is now no errors are displayed on the view, but the validation is working quite well. I suspect I have to insert some code where I have written "// Set errors on view" in the code. But what code do I need to put? I was not really able to find any clear answers to this - maybe I am just blind. I am looking forward to your help. Thank you.
My controller:
public class AccountController
{
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel1 model, string returnUrl)
{
public class LogOnModel1
{
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}
public class AccountValidator : AbstractValidator<LogOnModel1>
{
public AccountValidator()
{
RuleFor(x => x.UserName).NotNull().WithMessage("Brugernavn skal udfyldes").NotEmpty().WithMessage("Brugernavn skal udfyldes");
RuleFor(x => x.Password).NotNull().WithMessage("Kodeord skal udfyldes").NotEmpty().WithMessage("Kodeord skal udfyldes");
Custom(x => { return Membership.Provider.ValidateUser(x.UserName,x.Password) ? new ValidationFailure(null, "wrong password") : null; });
}
}
FluentValidation.Results.ValidationResult res = new Models.AccountValidator().Validate(model);
if (res.IsValid)
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
// Set errors on view
}
return View(model);
}
}
My model and validation class:
public class LogOnModel1
{
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}
public class AccountValidator : AbstractValidator<LogOnModel1>
{
public AccountValidator()
{
RuleFor(x => x.UserName).NotNull().WithMessage("Brugernavn skal udfyldes").NotEmpty().WithMessage("Brugernavn skal udfyldes");
RuleFor(x => x.Password).NotNull().WithMessage("Kodeord skal udfyldes").NotEmpty().WithMessage("Kodeord skal udfyldes");
Custom(x => { return Membership.Provider.ValidateUser(x.UserName,x.Password) ? new ValidationFailure(null, "wrong password") : null; });
}
}
and finally my view:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TelCountMVC.Models.LogOnModel1>" %>
<asp:Content ID="loginTitle" ContentPlaceHolderID="TitleContent" runat="server">
Log On
</asp:Content>
<asp:Content ID="loginContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>Log On</h2>
<p>
Please enter your username and password. <%: Html.ActionLink("Register", "Register") %> if you don't have an account.
</p>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %>
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName) %>
<%: Html.ValidationMessageFor(m => m.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Password) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.Password) %>
<%: Html.ValidationMessageFor(m => m.Password) %>
</div>
<div class="editor-label">
<%: Html.CheckBoxFor(m => m.RememberMe) %>
<%: Html.LabelFor(m => m.RememberMe) %>
</div>
<p>
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
<% } %>
</asp:Content>
I suspect that you have figured this out ages ago.
You lose model state if you call RedirectToAction. You have to return a view and pass the LogOnModel1 model into it.
Connect the view to your model instead of System.Web.Mvc.ViewPage and then in your controller do something like this:
if(! ModelState.IsValid) {
return View("Index", logOnModel1);
}
And here is a link to Jeremy Skinner's (the creator of Fluent Validation) description of how to set it up with MVC 2.
The contactAddModel.Search always comes through as null - any ideas?
View declaration
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<rs30UserWeb.Models.StatusIndexModel>" %>
ViewModels
public class StatusIndexModel
{
public ContactAddModel contactAddModel;
public StatusMessageModel statusMessageModel;
}
public class ContactAddModel
{
[Required(ErrorMessage="Contact search string")]
[DisplayName("Contact Search")]
public string Search { get; set; }
}
View content
<% using (Html.BeginForm("AddContact", "Status")) { %>
<div>
<fieldset>
<legend>Add a new Contact</legend>
<div class="editor-label">
<%= Html.LabelFor(m => m.contactAddModel.Search) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(m => m.contactAddModel.Search)%>
<%= Html.ValidationMessageFor(m => m.contactAddModel.Search)%>
</div>
<p>
<input type="submit" value="Add Contact" />
</p>
</fieldset>
</div>
<% } %>
Controller
[HttpPost]
public ActionResult AddContact(Models.ContactAddModel model)
{
if (u != null)
{
}
else
{
ModelState.AddModelError("contactAddModel.Search", "User not found");
}
return View("Index");
}
You should modify the action AddContact like this
AddContact(Models.ContactAddModel contactAddModel)
just replace "model" with "contactAddModel"