0

我有一個對象class Tag {string Key; string Text;}和一個綁定到存儲表的對象RecordMVC綁定到轉換後的屬性

class Record { [...Id & other properties...] 
    public string Name { get; set; } // "FirstRecord" 
    public string Tags { get; set; } // "3,4,9" 
} 

更新Name不存在問題。但是我在Tags ...上遇到了一些困難......正如你所看到的Tags屬性是int鍵的CSV(比如{1:".net",2:"java",3:"perl" ...})。

Record編輯視圖我建立與所有可用標籤的字典:

Dictionary<string, string> tags = ViewData["tags"] as Dictionary<string, string>; 
[...] 
<div class="form-group"> 
    <label class="col-md-2 control-label">Tags</label> 
    <div class="col-md-10"> 
     @foreach (var tag in tags) 
     { 
      <div class="checkbox-inline"> 
       <label for="[email protected]"> 
        <input type="checkbox" id="[email protected]" value="@tag.Key" /> 
        @tag.Value 
       </label> 
      </div> 
     } 
    </div> 
</div> 

最後,我有編輯後控制器,這樣

// POST: Records/Edit/5 
[HttpPost, ValidateAntiForgeryToken] 
public async Task<IActionResult> Edit(string id, [Bind("Id,Name")] Record record) 
{ 
    if (id != record.Id) { 
     return NotFound(); 
    } 

    if (ModelState.IsValid) { 
     try { 
      await repository.UpdateTableEntityAsync(record); 
     } 
     catch (Exception) { [...] } 

     return RedirectToAction("Index"); 
    } 
    return View(record); 
} 

所以,我我很困惑,如果我應該綁定Tags,就像[Bind("Id,Name,Tags")],因爲該值應該從所有選中的複選框值中取出,然後連接爲CSV以準備在s中進行更新torage ...

+0

存儲你的標籤爲CSV是不好的做法 - 指(https://stackoverflow.com/questions/3653462/is-storing-a [是存儲在數據庫中列分隔列表真的那麼糟嗎?] -de-list-in-a-database-column-really-that-bad) - 你應該有一個帶導航屬性的單獨表格。但就視圖而言,您應該爲您的視圖創建視圖模型,類似於[此答案](https://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-和拉出的IEnumerable/29554416#29554416) –

回答

0

如果要將複選框值綁定到字符串,可以獲取複選框的所有值並手動設置模型的值。以下代碼供您參考。

在視圖中,爲複選框添加名稱屬性。

<input type="checkbox" name="[email protected]" id="[email protected]" value="@tag.Key" /> 

在操作中,我們可以使用Request.Form獲取複選框的所有值。

[HttpPost, ValidateAntiForgeryToken] 
public async Task<IActionResult> Edit(string id, [Bind("Id,Name")] Record record) 
{ 
    if (id != record.Id) 
    { 
     return NotFound(); 
    } 

    record.Tags = ""; 
    foreach (var key in Request.Form.AllKeys) 
    { 
     if (key.StartsWith("tag_")) 
     { 
      record.Tags += Request.Form[key] + ","; 
     } 
    } 
    if (record.Tags.Length > 0) 
    { 
     record.Tags = record.Tags.Remove(record.Tags.Length - 1, 1); 
    } 

    if (ModelState.IsValid) 
    { 
     try 
     { 
      await repository.UpdateTableEntityAsync(record); 
     } 
     catch (Exception) 
     { 
     } 

     return RedirectToAction("Index"); 
    } 
    return View(record); 
}