0

オブジェクトclass Tag {string Key; string Text;}とオブジェクトRecordがストレージテーブルにバインドされています。MVC変換されたプロパティへのバインド

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

Nameを更新することは問題ありません。しかし、私はTagsでいくつかの問題を抱えています... Tagsのプロパティは、int keysの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

- 参照してくださいは、[本当に悪いデータベース列で区切られたリストを格納していますか?](https://stackoverflow.com/questions/3653462/is-storing-a -delimited-list-in-a-database-column-really-that-bad) - ナビゲーションプロパティを持つ別のテーブルが必要です。しかし、ビューに関する限り、あなたは[この回答](https://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-と同様)のようにビューのビューモデルを作成する必要があります。引き抜き不可能/ 29554416#29554416) –

答えて

0

チェックボックスの値を文字列にバインドする場合は、checkboxのすべての値を取得し、モデルの値を手動で設定できます。下記のコードは参照用です。

ビューでは、checkboxのnameプロパティを追加します。

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

実際には、Request.Formを使用してすべてのチェックボックスの値を取得できました。 CSVは悪い習慣であるとして、あなたのタグを保存

[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); 
} 
関連する問題