有没有办法利用 TempData 和 ActionLink 将数据从视图传递到控制器。我有一个具有客户端验证的视图,我需要在不使用提交按钮的情况下从页面上的文本框中更新下拉列表。当使用两个提交类型按钮时,客户端验证会标记所有尚未填写的字段。本质上,我希望能够将用户定义的类别添加到下拉列表中,而不必只为文本框跳转到不同的视图和提交按钮。
我不确定我是否可以做这样的事情:
<input type="text" name="NewCat" value="@TempData["newCat"]" placeholder="New Catagory"/>
虽然我无法让它工作......
风景:
@model Exercise4.Models.Quote
@{
ViewBag.Title = "Create";
}
<h2>Create New Quote</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Quotation Creation</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CatagoryID, "Catagory")
</div>
<div class="editor-field">
@Html.DropDownList("CatagoryID", String.Empty)
@Html.ValidationMessageFor(model => model.CatagoryID)
</div>
<aside>
@using (Html.BeginForm("NewCatagory","Quote"))
{
<input type="text" name="NewCat" value="@TempData["newCat"]" placeholder="New Catagory"/>
@Html.ActionLink("Add Catagory","NewCatagory","Quote")
}
</aside>
<div class="editor-label">
@Html.LabelFor(model => model.QName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.QName)
@Html.ValidationMessageFor(model => model.QName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.QAuthor)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.QAuthor)
@Html.ValidationMessageFor(model => model.QAuthor)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
控制器部分:
//
// Create New Catagory
public ActionResult NewCatagory()
{
string value = TempData["newCat"] as string;
if(!String.IsNullOrWhiteSpace(value))
{
Catagory cat = new Catagory();
cat.CatName = value;
db.Catagories.Add(cat);
db.SaveChanges();
}
ViewBag.CatagoryID = new SelectList(db.Catagories, "CatagoryID", "CatName");
return RedirectToAction("Create");
}
任何建议将不胜感激,无论是如何使这项工作或更优雅一点。