所以我有一个用户选择类别的下拉列表。但我想让它更加用户友好,以便自动选择category id
并将其发布在该类别中。
我的cshtml:
<div class="form-group">
@Html.LabelFor(model => model.category.Id, "category", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CategoryId", null, htmlAttributes: new { @class = "form-control", required = "" })
@Html.ValidationMessageFor(model => Model.category, "", new { @class = "text-danger" })
</div>
我的控制器:
public ActionResult Create()
{
ViewBag.CategoryId = new SelectList(db.Categorys, "Id", "Title", db.Categorys);
return View();
}
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,CategoryId,Content")] Thread thread)
{
if (ModelState.IsValid)
{
thread.ApplicationUserId = User.Identity.GetUserId();
db.Threads.Add(thread);
db.SaveChanges();
return RedirectToAction("Post", new { @id = thread.Id });
}
ViewBag.CategoryId = new SelectList(db.Categorys, "Id", "Title", thread.Id);
return View(thread);
}
我应该怎样做才能让它变得动态,以便用户不必选择category id
,但select
元素可以自行完成。
答案 0 :(得分:0)
使用DropDownListFor
并指定相应的模型属性来存储您的valun,它将为您完成。
@Html.DropDownListFor(m => m.CatId, Model.List, null)
其中CatId
是模型中的属性,List
是要在select
元素中显示为值的项目列表。您可以在第三个参数中为null
而不是id
指定此元素的其他html属性(例如class
,package MainComponents;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.Border;
import MainTab_TabbedPane.TopTabbedPane;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
public class TopPanel extends JPanel {
//DECLARATION
JButton logOutButton = new JButton("Logout");
TopTabbedPane topTabbedPane = new TopTabbedPane();
private final Border myLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
//CONSTRUCTOR
public TopPanel(){
setPanelInitialProperties();
addComponents();
}
//METHODS
private void setPanelInitialProperties(){
setLayout(new GridBagLayout());
setBorder(myLineBorder); //sets a Line Border for this panel
}
private void addComponents(){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
this.add(topTabbedPane); //adds TabbedPane holding Home, Administration... to this Top Panel
gbc.gridx = 0;
gbc.gridy = 0;
this.add(logOutButton);
}
}
)