2011-06-16 66 views
1

有什麼不對?模型始終爲空。無效且始終有效的模型傳遞到行動

控制器

[HttpGet] 
public ViewResult Add() 
{ 
    return View("Edit"); 
} 

[HttpPost] 
public ViewResult Add(Models.EditViewModel m) 
{ 
    if (ModelState.IsValid) 
    { 
     return View("Success"); 
    } 
    else 
    { 
     return View("Edit", m); 
    } 
} 

型號:

public class EditViewModel 
{ 
    [Required] 
    [Display(Name = "JobTitle", ResourceType = typeof(DisplayNames))] 
    public string Title { get; set; } 

    [Required] 
    [Display(Name = "JobDescription", ResourceType = typeof(DisplayNames))] 
    public string Description { get; set; } 
} 

查看

@model MyWebSite.Models.EditViewModel 
<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> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true, "Please correct the errors and try again.") 
    @Html.EditorForModel() 
    <input type="submit" value="Send" /> 
} 

渲染視圖

<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script> 
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script> 
<form action="/MyAction" method="post"><div class="editor-label"><label for="Title">Fun&#231;&#227;o</label></div> 
    <div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Informe um valor para Fun&amp;#231;&amp;#227;o" id="Title" name="Title" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span></div> 
    <div class="editor-label"><label for="Description">Descri&#231;&#227;o</label></div> 
    <div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Informe um valor para Descri&amp;#231;&amp;#227;o" id="Description" name="Description" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="Description" data-valmsg-replace="true"></span></div> 
<input type="submit" value="Send" /> 
</form> 
+0

那麼你的部分觀點是什麼樣子? – 2011-06-16 17:28:42

+0

你的意思是呈現的HTML?我只是把它。 – Eduardo 2011-06-16 17:33:31

+0

否視圖htat正在使用'@ Html.EditorForModel()' – 2011-06-16 17:34:45

回答

1

知道了! 問題是一個糟糕的路線,每次都在創建一個新模型。

改變

routes.MapRoute(
    "Add", // Route name 
    "AnnounceJob", // URL with parameters 
    new { controller = "Jobs", action = "Add", job = new Models.EditViewModel() } // Parameter defaults 
); 

routes.MapRoute(
    "Add", // Route name 
    "AnnounceJob", // URL with parameters 
    new { controller = "Jobs", action = "Add", job = UrlParameter.Optional } // Parameter defaults 
); 
+0

你甚至不需要參數。 – 2011-06-17 01:20:33

+0

如果這是您解決方案的答案,則應將其標記爲接受的答案。 – 2011-09-29 17:38:04