2015-11-04 65 views
1

我有proccess這種方法「製造」的形式在asp.net:如何處理隱藏的價值創造方法

public ActionResult Create([Bind(Include = "question_id, feedback_id")] feedback_questions feedback_questions) 

在形式question_id我從選擇框中獲取,但我feedback_id想隱藏,以獲取值。

我的形式:

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <h4>feedback_questions</h4> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
     <div class="form-group"> 
      @Html.LabelFor(model => model.question_id, "choose question: ", htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.DropDownList("question_id", null, htmlAttributes: new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.question_id, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
     <div class="form-group"> 
      @Html.LabelFor(model => model.feedback_id, "", htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       // here I want hidden attribute for feedback_id, which will have value @ViewBag.feedback_id 
       @Html.ValidationMessageFor(model => model.question_id, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Create" class="btn btn-default" /> 
      </div> 
     </div> 
    </div> 
} 

我該怎麼辦呢?

+1

爲什麼你使用viewbag如果屬性在你的模型上? – JamieD77

+0

在將模型傳遞給視圖(而不是在ViewBag中)並在視圖中使用@ Html.HiddenFor(m => m.feedback_id)之前,只需在控制器中設置'feedback_id'的值即可。注意,爲隱藏輸入添加標籤也沒有意義,正如生成一個ValidationMessageFor()(默認情況下未驗證隱藏輸入) –

回答

0

您可以使用Html.Hidden("feedback_id", @ViewBag.feedback_id)其中feedback_id是隱藏輸入的名稱,應該與您綁定的屬性的名稱相匹配。

1

也許feedback_id被傳遞到從另一個視圖或佈局視圖,但因爲它是你的模型,爲什麼不把它傳遞到創建視圖的獲取動作

public ActionResult Create() 
{ 
    return View(new feedback_questions() { feedback_id = ?? }); 
} 

[HttpPost] 
public ActionResult Create([Bind(Include = "question_id, feedback_id")] feedback_questions feedback_questions) 
{ 
    return View(feedback_questions);  
} 

那麼你可以只使用HiddenFor幫手

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 
    @Html.HiddenFor(model => model.feedback_id) 
    <div class="form-horizontal"> 
     <h4>feedback_questions</h4> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
     <div class="form-group"> 
      @Html.LabelFor(model => model.question_id, "choose question: ", htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.DropDownList("question_id", null, htmlAttributes: new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.question_id, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Create" class="btn btn-default" /> 
      </div> 
     </div> 
    </div> 
}