Fetch TagsInput from DB and Display on View in MVC

Mohammed Moeez 21 Reputation points
2022-05-11T03:51:52.52+00:00

I am having a problem fetching data from DB and displaying them on View in Edit. Assuming I have multiple tags in DB, I cannot fetch it on View.

Edit Controller //GET

public ActionResult Edit(int? id)  
        {  
            if (id == null)  
            {  
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
            }  
            NotesInList notesInList = db.NotesInLists.Find(id);  
            var tags = db.Tags.Where(x => x.Note_Id == id).FirstOrDefault();  
              
            if (notesInList == null)  
            {  
                return HttpNotFound();  
            }  
            NoteTagViewModel NTVM = new NoteTagViewModel()  
            {  
                Notes = notesInList,  
                TagsList = tags.ToString()  
            };  
            return View(NTVM);  
        }  

Notes Model

public class NotesInList  
    {  
        [Key]  
        public int NoteId { get; set; }  
  
        [Required]  
        [Display(Name = "Note Name")]  
        public string NoteName { get; set; }  
  
        [DataType(DataType.Date)]  
        [Display(Name = "Creation Date")]  
        public DateTime? CreationDate { get; set; }  
  
        [DataType(DataType.Date)]  
        [Display(Name = "Last Updated")]  
        public DateTime? UpdateDate { get; set; }  
  
        public string customFile { get; set; }  
  
        [Display(Name = "Enter Note Content")]  
        public string TextDescription { get; set; }  
  
        public List<Tags> Tags { get; set; }  
  
        public Lists List { get; set; }  
  
        public int ListId { get; set; }  
    }  

Notes View Model

public class NoteTagViewModel  
    {  
        [Key]  
        public int NoteId { get; set; }  
  
        [Required]  
        [Display(Name = "Note Name")]  
        public string NoteName { get; set; }  
  
        [DataType(DataType.Date)]  
        [Display(Name = "Creation Date")]  
        public DateTime? CreationDate { get; set; }  
  
        [DataType(DataType.Date)]  
        [Display(Name = "Last Updated")]  
        public DateTime? UpdateDate { get; set; }  
  
        public string customFile { get; set; }  
  
        [Display(Name = "Enter Note Content")]  
        public string TextDescription { get; set; }  
  
        //multiple tags  
        public string TagsList { get; set; }  
  
        public Lists List { get; set; }  
  
        public int ListId { get; set; }  
  
        public List<Tags> AllTags { get; set; }  
  
        public NotesInList Notes { get; set; }  
  
    }  

Edit View
@默 NoteBlocks.Models.NoteTagViewModel

@{
ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm("Edit", "NotesInLists", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
@azzedinehtmlsql .AntiForgeryToken()

<div class="form-horizontal">
<h4>NotesInList</h4>
<hr />
@azzedinehtmlsql .ValidationSummary(true, "", new { @class = "text-danger" })
@azzedinehtmlsql .HiddenFor(model => model.NoteId)

<div class="form-group">  
	@Html.LabelFor(model => model.Notes.NoteName, htmlAttributes: new { @class = "control-label col-md-2" })  
	<div class="col-md-10">  
		@Html.EditorFor(model => model.Notes.NoteName, new { htmlAttributes = new { @class = "form-control" } })  
		@Html.ValidationMessageFor(model => model.Notes.NoteName, "", new { @class = "text-danger" })  
	</div>  
</div>  
@if (Model.TextDescription == null && Model.customFile != null)  
{  
	<div class="form-group">  
		@Html.Label("File Upload", htmlAttributes: new { @class = "control-label col-md-2" })  
		<div class="col-md-10">  
			<input type="file" name="file" class="form-control" />  
		</div>  
	</div>  
}  
else  
{  
	<div class="form-group">  
		@Html.LabelFor(model => model.Notes.TextDescription, htmlAttributes: new { @class = "control-label col-md-2" })  
		<div class="col-md-10">  

			@Html.TextAreaFor(model => model.Notes.TextDescription, new { @class = "form-control", @cols = "50", @rows = "12", id = "TextDescription", name = "TextDescription" })  
			@Html.ValidationMessageFor(model => model.Notes.TextDescription, "", new { @class = "text-danger" })  
		</div>  
	</div>  
}  

<div class="form-group">  
	@Html.Label("Tags", htmlAttributes: new { @class = "control-label col-md-2" })  
    <div class="col-md-10">  
         
        <input type="text" id="tagsfield" name="tagsfield" class=form-control data-role="tagsinput" />  
        <input type="hidden" name="TagsList" id="TagsList" />  
    </div>  
</div>  

<div class="form-group">  
	<div class="col-md-offset-2 col-md-10">  
		<input type="submit" value="Save" class="btn btn-default" />  
	</div>  
</div>  

</div>
}

<div>
@azzedinehtmlsql .ActionLink("Back to List", "Index")
</div>

@section scripts
{
<script>

	$(document.body).on('focusout', '.bootstrap-tagsinput input', () => {  
	let array = $('#tagsField').tagsinput('items');  
	$("#TagsList").val(array);  
	})  
</script>      

}

I am not using JSON but for now want to handle it using Jquery. Please assist.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,412 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,629 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 28,836 Reputation points Microsoft Vendor
    2022-05-11T07:43:10.293+00:00

    Hi @Mohammed Moeez ,
    You can get the value directly, then you can bind itemAdded and itemRemoved.

       <select multiple data-role="tagsinput" id="testtaginput">  
                            @{  
                                foreach (var item in Model.TagsList)  
                                {  
                                    <option value="@item.Tags">@item.Tags</option>  
                                }  
                            }  
                        </select>  
    $("#testtaginput").on('itemAdded', function(event) {  
        console.log('item added : '+event.item);  
    });  
    $("#testtaginput").on('itemRemoved', function(event) {  
        console.log('item removed : '+event.item);  
    });  
    

    More information:
    https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful