Selectlist items are not displayed when edit data in ASPMVC core.

jewel 1,186 Reputation points
2023-08-14T10:57:35.08+00:00

I have two selectlists in my project. When inserting data it works correctly but when editing it doesn't show item in selectlist.

If any experienced would help me. I would benefit. thanks in advance


namespace aspCoreProject.Controllers
{
	public class DropdownController : Controller
	{
		private ApplicationDbContext _context;
		public DropdownController(ApplicationDbContext context)
		{
			_context = context;
		}
		public IActionResult Index()
		{
			var person = _context.persondatas.ToList();
			return View(person);
		}
		public JsonResult Country()
		{
			var country = _context.countries.ToList();
			return Json(country);
		}
		public JsonResult State(int id)
		{
			var State = _context.states.Where(x => x.ConuntryID == id).ToList();
			return Json(State);
		}
		public IActionResult insertrecord(persondata pm)
		{
			persondata data = new persondata();
			data.CountryID = pm.CountryID;
			data.StateID = pm.StateID;
			data.Name = pm.Name;
			_context.persondatas.Add(data);
			_context.SaveChanges();
			return View();
		}
		public IActionResult Edit(int IDs)
		{
			persondata model = new persondata();
			if (IDs > 0)
			{
				persondata emp = _context.persondatas.Where(x => x.ID == IDs).SingleOrDefault();
				model.ID = emp.ID;
				model.Name = emp.Name;
				model.CountryID = emp.CountryID;
				model.StateID = emp.StateID;

			}
			var data = _context.persondatas.Where(x => x.ID == IDs).SingleOrDefault();
			return PartialView("~/Views/Dropdown/_partialview.cshtml", model);
		}
	}
}

//index
@model IEnumerable<aspCoreProject.Models.persondata> 
<table class="table"> 	
<tr> 		
<th>Id</th> 		
<th>Name</th> 		
<th>CountryID</th> 		
<th>StateId</th> 		
<th>Action</th> 	
</tr> 	
@foreach (var item in Model) 	
{ <tr> 			
<td>@item.ID</td> 			
<td>@item.Name</td> 			
<td>@item.CountryID</td> 			
<td>@item.StateID</td> 			
<td><button onclick="Edit(@item.ID)">Edit</button></td> 		
</tr> 	}  
</table>	
<div> 		
<label>Person Name</label> 		
<input type="text" id="name" /> 
</div> 	
<div> 
<label>Country Name</label> 		
<select id="Country"> 			
<option>---Select Country Name----</option> 		
</select> 	
</div> 	
<div> 		
<label>State Name</label> 		
<select id="State"> 			
<option>---Select State Name----</option> 		
</select> 	
</div> 	
<div> 		
<button class="btn btn-primary" onclick="addata()">Save</button> 	
</div>   
<div class="modal fade" id="myModal1"> 	
<div class="modal-dialog"> 		
<div class="modal-content"> 			
<div class="modal-header"> 				
<a href="#" class="close" onclick="Cancel()" data-bs-dismiss="modal">&times</a> 				<h3 class="modal-title text-bg-success" id="heading">Insert record</h3> 			</div> 			
<div class="modal-body" id="myModalBodyDiv1"> 			
</div> 		
</div> 	
</div>
 </div> 
<script>  	
$(document).ready(function () 
{Country() 		
$('#State').attr('disabled', true); 		
$('#Country').change(function () 
{ $('#State').attr('disabled', false); 			
var id = $(this).val(); 			
$('#State').empty(); 			
$('#State').append('<option>---Select State Name----</option>'); 			$.ajax({ 				
url: '/Dropdown/State?id=' + id, 				
success: function (result) { 					
$.each(result, function (i, data) { 						$('#State').append('<option value=' + data.stateID + '>' + data.sName +'</option>'); 					
}); 				
} 			
}); 		
}); 	
}) 	
function Country() {
 		$.ajax({
 url: '/Dropdown/Country', 
success: function (result) {
$.each(result, function (i, data) 
{ $('#Country').append('<option value=' + data.countryID + '>' + data.name + '</option>'); 				
}); 			
} 		
}); 	
} 	
function addata() 
{ var formData = new FormData(); 		
formData.append("countryID", $("#Country").val()); 		formData.append("stateID", $("#State").val()); 		
formData.append("Name", $("#name").val()); 		
$.ajax({ type: 'POST', 			
url: '/Dropdown/insertrecord', 			
data: formData, 			
cache: false, 			
contentType: false, 			
processData: false, 			
success: function () { 				
alert("Saved") 			
}, 			
error: function () { 				
alert("Not Saved") 			
}  		
});  	
} 	
function Edit(Std) 
{ var url = "/Dropdown/Edit?IDs=" + Std;  		
$("#myModalBodyDiv1").load(url, function (data) { 			$("#myModal1").modal("show");  			
$('#heading').text('Insert Or Updae Record'); 		
}) 	} 
</script>

//_partialview.cshtml
@model aspCoreProject.Models.persondata 
<form >     
<div>         
<label>Person Name</label>         
<input asp-for="Name" id="name" />     
</div>     
<div>         
<label>Country Name</label>         
<select asp-for="CountryID" id="Country">             
<option>---Select Country Name----</option>         
</select>     
</div>     
<div>         
<label>State Name</label>         
<select asp-for="StateID" id="State">             
<option>---Select State Name----</option>         
</select>     
</div>     
<div>         
<button class="btn btn-primary" onclick="Update()">Update</button>     
</div>  
</form>  
//model
namespace aspCoreProject.Models 
{ 	public class persondata 	
{ 		
[Key] 		
public int ID { get; set; } 		
public int CountryID { get; set; } 		
public int StateID { get; set; } 		
public string Name { get; set; }	 	
Screenshot (3).png
Developer technologies ASP.NET ASP.NET Core
{count} votes

Accepted answer
  1. Anonymous
    2023-08-17T06:09:52.5133333+00:00

    Hi @jewel

    When inserting data it works correctly but when editing it doesn't show item in selectlist.

     		public IActionResult Edit(int IDs)
     		{
     			persondata model = new persondata();
     			if (IDs > 0)
     			{
     				persondata emp = _context.persondatas.Where(x => x.ID == IDs).SingleOrDefault();
     				model.ID = emp.ID;
     				model.Name = emp.Name;
     				model.CountryID = emp.CountryID;
     				model.StateID = emp.StateID;
    	    }
    	var data = _context.persondatas.Where(x => x.ID == IDs).SingleOrDefault();
    	return PartialView("~/Views/Dropdown/_partialview.cshtml", model);
    }
    

    The issue relates the Edit method and the JavaScript scripts.

    From your code, we can see you just return a persondata model to the partial view, without return the DropDownList options to the partial view. And in your JavaScript scripts, you will populate the DropDownList in the insert part using the Country() function, this action is executed before the Edit partial view loading, and in the Edit(Std) function, after loading the edit partial view, you also didn't find the DropDownList in the Edit partial view and populate it. So, the DropDownList in the edit partial view is empty.

    To solve this issue, you can use ViewBag to transfer the countries and states from Edit action to the partial view, then populate the DropDownList using ViewBag. Code like this:

    public IActionResult Edit(int IDs)
    {
        persondata model = new persondata();
        if (IDs > 0)
        {
            persondata emp = _context.persondatas.Where(x => x.ID == IDs).SingleOrDefault();
            model.ID = emp.ID;
            model.Name = emp.Name;
            model.CountryID = emp.CountryID;
            model.StateID = emp.StateID;
    
        }
        var data = _context.persondatas.Where(x => x.ID == IDs).SingleOrDefault();
    
        //used to populate the dropdownlist.
        ViewBag.countries = new SelectList(_context.countries.ToList(), "CountryID", "Name");
        ViewBag.state = new SelectList(_context.states.ToList(), "StateID", "sName");
    
        return PartialView("~/Views/Dropdown/_partialview.cshtml", model);
    } 
    

    And in the partial view, you can use asp-items to bind the DropDownList:

    @model aspCoreProject.Models.persondata
    <form>
        <div>
            <label>Person Name</label>
            <input asp-for="Name" id="name" />
        </div>
        <div>
            <label>Country Name</label>
            <select asp-for="CountryID" id="Country" asp-items="ViewBag.countries">
                <option>---Select Country Name----</option>
            </select>
        </div>
        <div>
            <label>State Name</label>
            <select asp-for="StateID" id="State" asp-items="ViewBag.state">
                <option>---Select State Name----</option>
            </select>
        </div>
        <div>
            <button class="btn btn-primary" onclick="Update()">Update</button>
        </div>
    </form>  
    

    Then, the result as below: after clicking the Edit button, the DropDownList is populated and has the default selected item.

    User's image

    Besides, you can also populate the edit partial view's DropDownList in the Edit(Std)function, after loading the partial view, use jquery to find the dropdownlist and then use jquery ajax to call the country action and populate the dropdownlist.

            function Edit(Std) {
                var url = "/Dropdown/Edit?IDs=" + Std;
                $("#myModalBodyDiv1").load(url, function (data) {
                    $("#myModal1").modal("show");
    
                    //use JQuery selector to find the DorpDownList in the partial view,
                    //then use JQuery ajax to call the /Dropdown/Country
    
                    $('#heading').text('Insert Or Updae Record');
                })
            }
    

    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.

    Best regards,

    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.