37
1
using System;
2
using System.ComponentModel.DataAnnotations;
3
using System.Web.Mvc;
4
using System.Collections.Generic;
5
6
namespace HelloWorldMvcApp
7
{
8
public class OrderViewModel
9
{
10
[Display(Name = "Order number")]
11
public int OrderNumber { set; get; }
12
[Display(Name = "Product")]
13
[Required(ErrorMessage = "Please select a product")]
14
public int SelectedProductId { get { return 2; }}
15
public SelectList ProductList { get; set; }
16
}
17
18
public class Product
19
{
20
public int ID { set; get; }
21
public string Name { set; get; }
22
}
23
24
public static class Repository
51
1
@model HelloWorldMvcApp.OrderViewModel
2
@{
3
Layout = null;
4
}
5
6
<!DOCTYPE html>
7
<!-- template from http://getbootstrap.com/getting-started -->
8
<html lang="en">
9
<head>
10
<meta charset="utf-8">
11
<meta http-equiv="X-UA-Compatible" content="IE=edge">
12
<meta name="viewport" content="width=device-width, initial-scale=1">
13
<title>Bootstrap 101 Template</title>
14
<!-- CSS Includes -->
15
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
16
<style type="text/css">
17
.field-validation-error {
18
color: #ff0000;
19
}
20
</style>
21
</head>
22
<body>
23
<div class="container">
24
<div class="col-md-6 col-md-offset-3">
36
1
using System;
2
using System.Web.Mvc;
3
using System.Collections.Generic;
4
5
namespace HelloWorldMvcApp
6
{
7
public class HomeController : Controller
8
{
9
[HttpGet]
10
public ActionResult Index()
11
{
12
OrderViewModel model = new OrderViewModel();
13
ConfigureViewModel(model);
14
return View(model);
15
}
16
[HttpPost]
17
public ActionResult Index(OrderViewModel model)
18
{
19
if (!ModelState.IsValid)
20
{
21
ConfigureViewModel(model);
22
return View(model);
23
}
24
// save and redirect
25
// but for testing purposes
26
ConfigureViewModel(model);
27
return View(model);
28
}
29
30
private void ConfigureViewModel(OrderViewModel model)
31
{
32
IEnumerable<Product> products = Repository.FetchProducts();
33
model.ProductList = new SelectList(products, "ID", "Name");
34
}
35
}
36
}