2011-08-22 45 views
0

我将查询字符串从外部源传递到我的帐户控制器,我想将这些值添加到模型并返回视图。下面的代码正在工作,但它返回的视图与缺失字段的所有验证错误。我只是喜欢它返回与填充这些字段的视图?返回填充字段的视图?

另一个问题是,我想返回一个干净的网址,例如/帐户/注册没有查询字符串在地址的末尾?

// ************************************** 
// URL: /Account/WriteRegistration/?Number=251911083837045755&Name=All&Remote=False 
// ************************************** 

    public ActionResult WriteRegistration(RegisterModel model, string Number, string Name, bool Remote) 
    { 
     model.Number = Number; 

     return View("Register", model); 
    } 

回答

2

我想你可能正在接近这一点。

如果您使用查询字符串来填充你的观点,而是执行此操作:

public ActionResult WriteRegistration(string Number, string Name, bool Remote) 
{ 
    // Instantiate a new model here, then populate it with the incoming values... 
    RegisterModel model = new RegisterModel() { Number = Number, Name = Name, Remote = Remote }; 
    return View("Register", model); 
} 

如果你正在寻找一个干净的URL,你可能要考虑使用POST,而不是...即创建一个表单并通过提交按钮进行提交。在这种情况下,你会这样做:

[HttpPost] 
public ActionResult WriteRegistration(RegisterModel model) 
{ 
    // Model binding takes care of this for you, no need to set it up yourself. 
    // ...but I'm guessing you'd do some logic here first. 
    return View("Register", model); 
} 

我认为你的原始代码是混合两种方法。

-1

我相信你可以调用ModelState.Clear()来清除ModelBinding产生的任何错误。这应该在第一次加载该页面时摆脱验证错误。

1

要返回干净的网址,你需要映射的路线,在Global.asax中添加以下在RegisterRoutes顶部:

routes.MapRoute(
    "WriteRegistration", 
    "Account/WriteRegistration/{Number}/{Name}/{Remote}", 
    new {controller="Account", action="WriteResistration"}, 
    new {productId = @"\d+" } 
); 

然后/Account/WriteRegistration/251911083837045755/All/False将匹配。

要将值传入视图,请通过viewdata传递它们,并将表单域的默认值设置为viewdata中的值。