Hi nagpureneha44,
After saving the file you need to call the Showdata method using Ajax to refresh the data.
While saving the data don't use tilde (~) symbol.
command.Parameters.AddWithValue("@ImageFile", "/User_images/" + fileName);
Modified code.
Controller
namespace Sprint2_BiodataForm.Controllers
{
public class BiodataController : Controller
{
// GET: Biodata
public ActionResult Index()
{
return View();
}
private string connectionString = @"data source= localhost\SQLEXPRESS01; initial catalog=Biodata; integrated security=true;";
[HttpPost]
public ActionResult InsertData(UserBiodata model)
{
try
{
// Check if the model state is valid (e.g., required fields are filled)
if (ModelState.IsValid)
{
if (model.ImageFile != null && model.ImageFile.ContentLength > 0)
{
string uploadDirectory = Server.MapPath("~/User_images/"); // Get the absolute server path
string fileName = Path.GetFileName(model.ImageFile.FileName);
string filePath = Path.Combine(uploadDirectory, fileName);
// Save the uploaded image to the specified absolute server path
model.ImageFile.SaveAs(filePath);
// Insert data into the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO UserBiodata (Name, ImageFile) VALUES (@Name, @ImageFile)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", model.Name);
command.Parameters.AddWithValue("@ImageFile", "/User_images/" + fileName); // Save the file path in the database
command.ExecuteNonQuery();
}
}
return Content("Data inserted successfully!");
}
else
{
return Content("Invalid data. Please check your inputs.");
}
}
catch (Exception ex)
{
return Content("Error: " + ex.Message);
}
}
[HttpPost]
public ActionResult Showdata()
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM UserBiodata";
SqlCommand command = new SqlCommand(query, connection);
List<UserBiodata> userList = new List<UserBiodata>();
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "dt");
userList = FillDataFromDsIntoModel(ds);
return Json(userList);
}
}
catch (Exception ex)
{
throw ex;
}
}
private List<UserBiodata> FillDataFromDsIntoModel(DataSet ds)
{
List<UserBiodata> lstUser = new List<UserBiodata>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
lstUser.Add(new UserBiodata()
{
Uid = Convert.ToInt32(dr[0]),
Name = dr[1].ToString(),
ImageFile = null, // Initialize as null since you're not retrieving the file here
ImageFilePath = dr["ImageFile"] != DBNull.Value ? dr["ImageFile"].ToString() : string.Empty
});
}
return lstUser;
}
}
}
View
<h2></h2>
<h1>Biodata Form</h1>
<div>
<label for="Name">Name:</label>
<input type="text" id="Name" />
</div>
<div>
<label for="ImageFile">Image:</label>
<input type="file" id="ImageFile" name="ImageFile" />
</div>
<button id="submitBtn">Submit</button>
<div id="result"></div>
<div id="DivLoad"></div>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script>
$(document).ready(function () {
PopoulateData();
var renderUserData = function (userdata) {
var strHtml = '';
strHtml += '<table border=1>';
strHtml += '<tr>';
strHtml += '<th>User Id</th>';
strHtml += '<th>Name</th>';
strHtml += '<th>Image</th>';
strHtml += '</tr>';
$.each(userdata, function (key, val) {
strHtml += '<tr>';
strHtml += '<td>' + val.Uid + '</td>';
strHtml += '<td>' + val.Name + '</td>';
strHtml += '<td><img src="' + val.ImageFilePath + '" a width="100" height="100" /></td>';
strHtml += '</tr>';
});
strHtml += '</table>';
$('#DivLoad').html(strHtml);
}
$("#submitBtn").click(function () {
var name = $("#Name").val();
var ImageFile = $("#ImageFile")[0].files[0];
// Create a FormData object to send the file
var formData = new FormData();
formData.append("Name", name);
formData.append("ImageFile", ImageFile);
$.ajax({
type: "POST",
url: "/Biodata/InsertData",
data: formData,
contentType: false, // Important: Prevent jQuery from setting contentType
processData: false, // Important: Prevent jQuery from processing the data
success: function (response) {
// Handle the response here
$("#result").html(response);
PopoulateData();
},
error: function (response) {
$("#result").html(response.responseText);
}
});
});
function PopoulateData() {
$.ajax({
url: '/Biodata/Showdata',
type: 'post',
success: function (data) {
//console.log(data);
// Loop through the data and append it to the table
renderUserData(data);
},
error: function (response) {
// Handle errors
console.error(response.responseText);
}
});
}
});
</script>