我需要一些基本面的帮助......
我有这个控制器,用一个类的实例来提供我的视图(至少我认为它是如何工作的).因为我给我的视图一个新的对象实例,为什么它必须为我的帖子创建一个更新的模型绑定?请看下面的例子.
[HttpGet]
public ActionResult Index(){
int hi = 5;
string temp = "yo";
MyModel foo = new MyModel(hi, temp);
return View(foo);
}
[HttpPost]
public ActionResult Index(MyModel foo){
MyModel poo = foo;
if(poo.someString == laaaa)
return RedirctToAction("End", "EndCntrl", poo);
else
throw new Exception();
}
View:
@model myApp.models.MyModel
@html.EditorFor(m => m.hi)
<input type="submit" value="hit"/>
Model:
public class MyModel {
public int hi {get; set;}
public string someString {get; set;}
public stuff(int number, string laaaa){
NumberforClass = number;
someString = laaaa;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我需要一个空白构造函数?此外,如果我有一个无参数构造函数,为什么poo.someString在我到达时会改变RedirctToAction("End", "EndCntrl", poo)?
为什么我需要一个空白构造函数?
因为
[HttpPost]
public ActionResult Index(MyModel foo){ ... }
Run Code Online (Sandbox Code Playgroud)
您要求绑定器在Post上为您提供具体实例,因此绑定器需要为您创建该对象.您的原始对象不会在GET和POST操作之间保留,只有(某些)其属性作为HTML字段存在.这就是"HTTP无国籍"的含义.
当你使用较低级别时,它会变得更加明显
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var Foo = new MyModel();
// load the properties from the FormCollection yourself
}
Run Code Online (Sandbox Code Playgroud)
为什么poo.someString会在我到达时改变
RedirctToAction("End", "EndCntrl", poo)?
因为someString未在您的视图中使用.因此,当您获得新模型时,它将永远是空白的.改变这种情况:
@model myApp.models.MyModel
@html.HiddenFor(m => m.SomeString)
@html.EditorFor(m => m.hi)
<input type="submit" value="hit"/>
Run Code Online (Sandbox Code Playgroud)
这会将值存储为HTML中的隐藏字段,并在POST时为您恢复.
| 归档时间: |
|
| 查看次数: |
3439 次 |
| 最近记录: |