[英]ASP.Net MVC ListBoxFor - Let user add items
我的應用程序當前包含幾個類-告訴您重要的類:
條目
public class Entry{
public IEnumerable<Hardware> RequestedHardware {get; set;}
}
public class Hardware{
public string Name {get; set;}
public bool IsAvailable {get; set;}
}
創建新的數據集(新條目)時,我希望用戶能夠向該條目添加新的硬件設備(一個列表框以顯示當前添加的內容,以及一個帶有按鈕的文本框,以將“設備”添加到列表框中)。 單擊“提交”按鈕后,應將所有添加的設備轉移到控制器中的“創建發布方法”。
我完全不知道要搜索什么,也不知道如何從這里開始-甚至可能嗎?
如果我不得不猜測,我會說我必須使用@ Html.ListBoxFor,但是正如我所說,我對此不確定。
編輯1
我將嘗試逐步解釋:
我將在今天下午添加所有必要的模型來解釋這種情況。
編輯2
模型
public class Entry{
public Employee Employee {get; set;}
public IEnumerable<Hardware> Hardware {get; set;}
}
public class Employee{
public string Firstname {get; set;}
public string Lastname {get; set;}
}
public class Hardware{
public string Name {get; set;}
public bool IsAvailable {get; set;}
}
控制器:
public ActionResult Create(Entry entry){
//I want to be able to access entry.Hardware here
}
HTML-用戶(頁面的查看者)可以創建一個新的條目-該條目由一個Employee和n個硬件組成。
<table class="table table-bordered table-hover table-striped">
<tr>
<th colspan="2" class="info">
Hardware data
</th>
</tr>
<tr>
<td>
@Html.ListBoxFor(o => o.Hardware, xxx) @* Here all Hardware the User adds should be shown *@
</td>
</tr>
<tr>
<td>
@Html.TextBoxFor(o => o.Hardware.Name) @* If a user wants to add a new Hardware here he has to add its text *@
</td>
<td>
<button class="btn btn-primary" value="Add Hardware"/> @* To save the above entered Hardware click here *@
</td>
</tr>
</table>
編輯3
<input type="text" id="my-textbox">
@Html.ListBoxFor(o => o.RequestedHardware, new List<SelectListItem>())
<a href='#' class="btn btn-primary action-add-to-list">Add Text To List</a>
<script>
$('.action-add-to-list').click(function () {
var newListValue = $('#my-textbox').val();
if ($.trim(newListValue) != '')
{
$('#RequestedHardware').append('<option>' + newListValue + '</option>');
$('#RequestedHardware').val('');
}
});
</script>
這部分解決了我的問題-現在,我希望能夠將所有都作為硬件類型的對象進行傳輸(選項文本是Hardware.Name,Hardware.IsAvailable的值應始終為false)
有適當的解決方案嗎?
您要說的是一個組合框,您可以在其中鍵入或從現有列表中進行選擇。 您不能為此使用列表框。 您需要一個常規文本字段。 現有項目將由數據列表(如果可以使用HTML5)或AJAX查詢提供。
使用數據列表的示例:
<label> Hardware <input list="hardware" name="hardware" /> </label> <datalist id="hardware"> <option value="Hammer"> <option value="Nails"> <option value="Wrench"> <option value="Pliers"> <option value="Screwdriver"> <option value="Drill"> </datalist>
唯一的問題是,這是HTML 5中的新功能,因此您的用戶將需要使用支持該功能的現代瀏覽器。 不過,您可以使用polyfill向至少一些較小的瀏覽器添加支持。 這是一個這樣的polyfill 。 可能還有其他人。
另外,您也可以使用任何隨機組合框JavaScript插件 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.