MVC3 DataAnnotations ServerSide Validation - asp.net-mvc-3

So im new to MVC3 and expirimenting with DataAnnotations for the validation.
All is working fine clientside, but how do I get the serverside version working?
If I disable Javascript then there are no validations to be seen.
My Model looks like this
[Required(ErrorMessageResourceName = "Verplicht", ErrorMessageResourceType = typeof (ValidatieStrings))]
[Display(Name="Voorletters", ResourceType = typeof (VeldNaamStrings))]
public string Voorletters { get; set; }
My Controller looks like this
using System.Web.Mvc;
using inschrijven_werknemer.Models;
namespace inschrijven_werknemer.Controllers
{
public class HomeController : LocalizationController
{
public ActionResult Index()
{
return View(new MedewerkInfoModel());
}
}
}
And my View looks like this
#model inschrijven_werknemer.Models.MedewerkInfoModel
<div class="stap-div" id="stap2">
#Html.EditorForModel("MedewerkInfoModel")
</div>
What am I doing wrong?

you can do something like this... using Model.IsValid property.
So you could try this:
[HttpPost]
public ActionResult Index()
{
if (ModelState.IsValid)
{
return View(new MedewerkInfoModel());
}
return View();
}
A more detailed read is available here : https://stackoverflow.com/a/5969156/1182982 and https://stackoverflow.com/a/4760494/1182982

Related

Passing data from view to controller MVC3

I recently came across the MVC tutorial on ASP.Net. I was trying to create a similar project (MVC3 Razor) where you can register the details. However, when I click the submit button the values of all properties in the parameter User is always null. I'm not able to figure out why the data is not getting passed from the view to the controller.
Even in the tutorial in the Create.cshtml they just use the Submit button as
<input type="submit" value="Create" />
and the code in Create Action in MoviesController.cs is as follows
[HttpPost]
public ActionResult Create(Movie movie)
{
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
In this tutorial when I submit, I get the form data in parameter movie. However, In my sample project I get it as null. I'm new to MVC and it would be great if you could help me our with this. Please find my code below.
Register.cshtml - While creating this view I have selected "Create a strongly-typed view" option and the Scaffold template option as "Empty"
#model MvcRegister.Models.User
#using (Html.BeginForm())
{
<div>
<div>Name</div><div>#Html.EditorFor(model => model.Name)</div>
<div>Email</div><div>#Html.EditorFor(model => model.Email)</div>
<div>Phone</div><div>#Html.EditorFor(model => model.Phone)</div>
<div><input type="submit" value="Register" /></div>
</div>
}
RegisterController.cs
public class RegisterController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(User user)
{
return RedirectToAction("Index");
}
}
User.cs
public class User
{
[Required]
public string Name;
[Required]
public string Email;
[Required]
public string Phone;
}
My project Source code available at http://www.filedropper.com/mvcregister and the Sample Movie project at http : //www.filedropper.com/mvcmovie
Change your User class as below. You have missed getter and setter.
public class User
{
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Phone { get; set; }
public string IP { get; set; }
public string Password { get; set; }
}
And also you need to add following java-scripts to get the validation work.
<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>
Thanks!

html.dropdownlistfor() troubles...getting null reference exceptions

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);
}

cant render view via renderAction

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

Howcome I populate selectlist with list of categories

What I want to do is to populate SelectList with categories from a categories repository.
A little mockup http://mockupbuilder.com/App/15379.
What I have now is a controller:
[HandleError]
public class ProductController : Controller {
private IRepository<Product> exhibitions;
private IRepository<Category> categories;
private readonly Int32 PageSize = 18;
// ctor ...
[HttpPost]
public ActionResult Create(Product product, Guid categoryId) {
// validation ...
// properties setting ...
product.Category = categories.Get(categoryId);
return View(product);
}
Category class is like this:
public class Category : AbstractEntity<Category> {
public String Title { get; set; }
public String Description { get; set; }
}
How do I populate a SelectList? How do I make this using JSON?
Thanks!
You can put the List in viewbag and render it using aspx code. Something like below:
[HttpGet]
public ActionResult Create() // your create page render action
{
Viewbag.CategoryList = categories.GetAll(); //put it into viewbag
return View();
}
And in your view page, something like this:
<select name="categoryId"> <%-- use name attribute to bind action parameters and model --%>
<%foreach (Category item in Viewbag.CategoryList)
{ %>
<option value="<%=item.Id %>"><%=item.Title %></option>
<% } %>
</select>
If you want to populate the categories via json.
You have to write a new action in your category controller like:
public class CategoryContrller : Controller{
....
[HttpGet]
public ActionResult GetAll()
{
var categories = categories.GetAll(); //put it into viewbag
return Json(categories, JsonRequestBehavior.AllowGet);
}
}
And in your page's js logic use ajax to call it and handle the result.

show div after submitting the form in MVC3

When the user clicks the submit button on a form I want to return a success / failure message on the form show me the demo
You could use a view model:
public class MyViewModel
{
public string Message { get; set; }
}
and then have a controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(FormCollection fc)
{
var model = new MyViewModel
{
Message = "some message"
};
return View(model);
}
}
and a view:
#model MyViewModel
#if (!string.IsNullOrEmpty(Model.Message))
{
<div>#Model.Message</div>
}
#using (Html.BeginForm())
{
<button type="submit">OK</button>
}

Resources