Hi,
I have implemented in an form to upload a file in my project MVC asp net c#
Upload the file is not mandatory.
My problem:
- when don't upload file I have confirmation that the values of form they where stored on database
- If I upload file instead I don't have confirmation that the values of form they where stored on database, despite the fact that the values are registered in the database
How to do resolve this?
view
<script type="text/javascript">
$(function () {
var msg = '@ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("Ok");
var url = "@Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
controller
[HttpPost]
public ActionResult Index(PersonModel person, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
var fileExtension = System.IO.Path.GetExtension(file.FileName);
if (fileExtension.ToString() == ".jpeg" ||
fileExtension.ToString() == ".jpg" ||
fileExtension.ToString() == ".gif" ||
fileExtension.ToString() == ".png")
{
fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fileName.Trim() + fileExtension;
var userfolderpath = System.IO.Path.Combine(Server.MapPath("~/UploadedFiles/"), fileName);
file.SaveAs(userfolderpath);
MTsqlinsert(person);
}
else
{
TempData["Message"] = "Please upload only image (jpg,gif,png)";
}
}
else
{
MTsqlinsert(person);
}
if (ModelState.IsValid)
{
return View(person);
}
return View(person);
}
private void MTsqlinsert(PersonModel person)
{
try
{
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
using (MySqlConnection con =
new MySqlConnection(constr))
{
using (MySqlCommand command =
new MySqlCommand("SP", con))
{
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
con.Open();
ViewData["result"] = command.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
string message = string.Format("<b>Message:</b> {0}<br /><br />", ex.Message);
message += string.Format("<b>StackTrace:</b> {0}<br /><br />", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>Source:</b> {0}<br /><br />", ex.Source.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>TargetSite:</b> {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
ModelState.AddModelError(string.Empty, message);
}
}