public class myViewModel{public string SelectedValue {get;set;}public void Post(){//due to MVC model binding the SelectedValue string above will be set by MVC model binding on post back.//this allows you to do something with it.DoSomeThingWith(SelectedValue);SelectedValue = "Thanks for update!";}}
[HTTPPOST]public ActionResult MyPostBackMethod (myViewModel mvm){if (ModelState.IsValid){// Immediately call the only method needed in VM...mvm.Post()}return View(mvm);}
如果你做MVC,这很棒,然后确保你的控制器是可管理的,并完全控制你的视图。如果你有一个大的视图,考虑向具有不同控制器的视图添加控件。只是不要将这些控制器级联到不同的控制器上。维护非常令人沮丧。花点时间,以一种将作为单独组件工作的方式单独设计事物……并且总是让控制器告诉模型提交或持久存储。MVC的理想依赖设置是查看←控制器→模型或ASP.NET(不要让我开始)模型←视图↔控制器→模型(其中模型可以是控制器到视图的相同或完全不同的模型)……当然,此时唯一需要知道Controller in View的主要是端点参考,以知道返回哪里传递模型。
class CustomView: UIView {var viewModel = MyViewModel {didSet {self.color = viewModel.viewColor}}
convenience init(viewModel: MyViewModel) {self.viewModel = viewModel}}
struct MyViewModel {var viewColor: UIColor {didSet {colorChanged?() // This is where the binding magic happens.}}
var colorChanged: ((UIColor) -> Void)?}
class MyViewController: UIViewController {
let myViewModel = MyViewModel(viewColor: .green)let customView: CustomView!
override func viewDidLoad() {super.viewDidLoad()
// This is where the binder is assigned.myViewModel.colorChanged = { [weak self] color inprint("wow the color changed")}customView = CustomView(viewModel: myViewModel)self.view = customView}}