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.
Related
I am trying to put a checkboxlist onto a simple form in asp.NET MVC 2. This is the code for it:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("HandSurvey", "Resources", FormMethod.Post, new { runat="server" }))
{ %>
<asp:CheckBoxList id="chkListChemical" runat="server">
<asp:ListItem>Fiberglass & resins</asp:ListItem>
<asp:ListItem>Heavy duty oil paints & stains</asp:ListItem>
<asp:ListItem>Mechanics - tools, grease/oil</asp:ListItem>
<asp:ListItem>Metalworking fluids</asp:ListItem>
<asp:ListItem>Paint & Stains in use</asp:ListItem>
<asp:ListItem>Exposure to solvents</asp:ListItem>
<asp:ListItem>Difficult soils</asp:ListItem>
<asp:ListItem>Hydrocarbons</asp:ListItem>
</asp:CheckBoxList>
<% }
%>
</asp:Content>
When I hit this page it gives this error:
Control 'ctl00_MainContent_chkListChemical_0' of type 'CheckBox' must be placed inside a form tag with runat=server.
I thought I was specifying the runat attribute correctly. Or is there something else that I am missing here? If I don't use the helper class and just use a regular form tag, it works.
In ASP.NET MVC you should avoid using server controls. Basically everything that has the runat="server" should not be used (except the content placeholder in WebForms view engine). In ASP.NET MVC you design view models:
public class MyViewModel
{
[DisplayName("Fiberglass & resins")]
public bool Item1 { get; set; }
[DisplayName("Heavy duty oil paints & stains")]
public bool Item2 { get; set; }
...
}
then you have controller actions that manipulate the view model:
// Action that renders the view
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
// Handles the form submission
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO: Process the results
return View(model);
}
and finally you have a strongly typed view:
<% using (Html.BeginForm("HandSurvey", "Resources")) { %>
<div>
<%= Html.CheckBoxFor(x => x.Item1) %>
<%= Html.LabelFor(x => x.Item1) %>
</div>
<div>
<%= Html.CheckBoxFor(x => x.Item2) %>
<%= Html.LabelFor(x => x.Item2) %>
</div>
...
<p><input type="submit" value="OK" /></p>
<% } %>
UPDATE:
As requested in the comments section in order to have those checkboxes dynamically generated from a database it is a simple matter of adapting our view model:
public class ItemViewModel
{
public int Id { get; set; }
public string Text { get; set; }
public bool IsChecked { get; set; }
}
and now we will have our controller action to return a list of this view model:
public ActionResult Index()
{
// TODO: obviously those will come from a database
var model = new[]
{
new ItemViewModel { Id = 1, Text = "Fiberglass & resins" },
new ItemViewModel { Id = 2, Text = "Heavy duty oil paints & stains" },
};
return View(model);
}
and the view will now simply become:
<% using (Html.BeginForm("HandSurvey", "Resources")) { %>
<%= Html.EditorForModel() %>
<p><input type="submit" value="OK" /></p>
<% } %>
and the last part would be to define an editor template for our view model (~/Views/Shared/EditorTemplates/ItemViewModel.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.ItemViewModel>"
%>
<div>
<%= Html.HiddenFor(x => x.Id) %>
<%= Html.CheckBoxFor(x => x.IsChecked) %>
<%= Html.DisplayFor(x => x.Text) %>
</div>
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.
Using the following model, I expect that when the Submit button is hit, the Edit Method to Fire, and the model parameter to have the adjusted values. But it keeps returning an instance of the class with all null values. It is as if no model binding ever happens.
class Trait
{
string Name { get; set; }
// other properties
}
class DesignViewModel
{
Dictionary<Trait, int> Allocation { get; set; }
}
Controller
public ActionResult Create()
{
var model = new DesignViewModel();
// retrieve traits from database
foreach(var trait in Repository.Traits)
model.Allocation.Add(trait, 0);
return View(model);
}
[HttpPost]
public ActionResult Edit(DesignViewModel model)
{
// nothing works yet, so I don't have a lot of code here...
}
HTML
Top Level Page
<%# Page Title="" Language="C#" MasterPageFile="~/Areas/Setup/Views/Shared/Setup.master"
Inherits="System.Web.Mvc.ViewPage<OtherModel>" %>
<% Html.RenderAction("Design", "Test"); %>
Partial View
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DesignViewModel>" %>
<% using (Html.BeginForm("Edit", "Test", FormMethod.Post ) ) {%>
<div id="eq">
<% foreach (var trait in Model.Allocations) { %>
<div style="margin: 15px;">
<%: trait.Key.Name %>
<br />
<span class="slider"></span>
<%: Html.TextBox(trait.Key.Name, trait.Value, new { #class = "spent" , #readonly = "readonly" })%>
</div>
<% } %>
</div>
<p>
<input type="submit" value="Submit" />
</p>
<% } %>
You need to add [HttpPost] to your Edit method for it to be fired during POST requests.
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.
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);