Hello I am trying something in which I am not really an expert and only have reached so far with great help.
I have a table and a form such as this
!https://imgur.com/a/MIb112p
the table is populated by a datatable i stored in a session while the form is goes to a [httppost] method. my problem is when i click the save button the form data is being saved but not the table
my view looks like this
#using cgs.Models;
#model ConfirmOrderCustomModel
#using System.Data;
#using System.Net;
#{
ViewBag.Title = "EditProduct";
Layout = "~/Views/Shared/DashboardLayout.cshtml";
}
<div id="form-wrapper" class="page-wrapper">
<div id="overview-row" class="row">
<div class="col-lg-12">
<h1 class="page-header">Confirm Order</h1>
</div>
</div>
<div id="form-div" class="row edit-form">
#using (Html.BeginForm("ConfirmOrder", "Product", FormMethod.Post))
{
#Html.AntiForgeryToken()
#*#Html.ValidationSummary(false, "", new { #class = "text-danger" })*#
<div class="row">
<div class="col-lg-8">
<table id="calculate-table" class="rwd-table">
<tr>
<th>ID</th>
<th>Order Units</th>
<th>Total</th>
<th>Discount</th>
<th>Net</th>
</tr>
#{
if (Session["tblCart"] != null)
{
DataTable dt = (DataTable)Session["tblCart"];
foreach (DataRow row in dt.Rows)
{
<tr>
#foreach (DataColumn col in dt.Columns)
{
<td>#row[col.ColumnName]</td>
}
<td><input type="button" value="Remove" onclick="Remove(this)" /></td>
</tr>
}
}
}
</table>
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.ShippingDate, new { htmlAttributes = new { #placeholder = "Shipping Date", #id = "lblShippingDate", #class = "label" } })
#Html.EditorFor(model => model.Orders.ShippingDate, new { htmlAttributes = new { #type = "date", #min = 0, #value = "", #placeholder = "Shipping Date", #name = "shippingDate", #id = "shippingDate", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.ShippingDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.OrderTotal, new { htmlAttributes = new { #placeholder = "Total", #id = "lblTotal", #class = "label" } })
#Html.EditorFor(model => model.Orders.OrderTotal, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Total", #name = "total_price", #id = "total_price", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.OrderTotal, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerName, new { htmlAttributes = new { #placeholder = "Customer", #id = "lblCustomer", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerName, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Customer", #name = "cust_name", #id = "cust_name", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerPhone, new { htmlAttributes = new { #placeholder = "CustomerPhone", #id = "lblPhone", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerPhone, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Customer Phone", #name = "cust_phone", #id = "cust_phone", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerEmail, new { htmlAttributes = new { #placeholder = "Email", #id = "lblEmail", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerEmail, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Email", #name = "cust_email", #id = "cust_email", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.DeliveryAddress, new { htmlAttributes = new { #placeholder = "Delivery Address", #id = "lblAddress", #class = "label" } })
#Html.EditorFor(model => model.Orders.DeliveryAddress, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Address", #name = "cust_address", #id = "cust_Address", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.DeliveryAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-offset-4 col-md-4">
<button id="btnSave" name="action" value="confirm">Confirm Order</button>
</div>
</div>
}
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
jQuery(document).ready(function() {
setTimeout(function() {
var sum1 = 0;
$("#calculate-table tr").not(':first').each(function () {
sum1 += getnum($(this).find("td:eq(4)").text());
function getnum(t) {
if (isNumeric(t)) {
return parseInt(t, 10);
}
return 0;
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
});
$("#total_price").val(sum1);
}, 1000);
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
//Get the reference of the Table.
var table = $("#calculate-table")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
};
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var orderProducts = new Array();
$("#calculate-table tr").each(function () {
var row = $(this);
var products = {};
products.ProductID = row.find("td").eq(0).html();
products.OrderUnits = row.find("td").eq(1).html();
products.TotalSum = row.find("td").eq(2).html();
products.DiscountVal = row.find("td").eq(3).html();
products.NetSum = row.find("td").eq(4).html();
orderProducts.push(products);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Product/ConfirmOrder",
data: JSON.stringify(orderProducts),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
});
});
</script>
and my actionresult like this
[HttpPost]
public JsonResult ConfirmOrder(ConfirmOrderCustomModel model)
{
using(dbcontext = new CDBContext())
{
dbcontext.Orders.Add(new Model.Orders
{
ShippingDate = model.Orders.ShippingDate,
OrderTotal = model.Orders.OrderTotal,
CustomerName = model.Orders.CustomerName,
CustomerPhone = model.Orders.CustomerPhone,
CustomerEmail = model.Orders.CustomerEmail,
DeliveryAddress = model.Orders.DeliveryAddress,
OrderStatus = true
});
dbcontext.SaveChanges();
int id = dbcontext.Orders.Max(odr => odr.ID);
DataTable dt = (DataTable)Session["tblCart"];
List<DataRow> list = new List<DataRow>(dt.Select());
foreach (var item in model.SalesModel)
{
dbcontext.OrderProducts.Add(new OrderProducts
{
OrderUnits = item.OrderUnits,
TotalSum = item.TotalSum,
DiscountVal = item.DiscountVal,
NetSum = item.NetSum,
ProductID = item.ProductID,
OrderID = id
});
dbcontext.SaveChanges();
}
return Json(new
{
redirectUrl = Url.Action("Dashboard", "Admin"),
isRedirect = true
});
}
}
any help is appreciated
Related
I have a registration form and there is two inputs for password and password confirmation. When I enter distinct values I wanted it to show the error message as 'Passwords should match' or something. So I googled it and found out that update-package should fix this problem. Then I applied this solution in order to fix my problem, now, neither my error message shows up nor my submit button works.
My Registration View:
<div class="container-fluid">
#using (Html.BeginForm("Register", "User", FormMethod.Post, new { #class = "col-12" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal p-3 m-3 w-100 d-flex flex-column align-items-center">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group w-100">
<label class="form-control-label col-md-12">Kullanıcı adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.kullaniciAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.kullaniciAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Firma adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.firmaAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.firmaAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifre, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre tekrar</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifreTekrar, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">E-mail</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.mail, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "text" } })
#Html.ValidationMessageFor(model => model.User.mail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Telefon</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.telefon, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.telefon, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Ülkeniz</label>
#Html.EditorFor(model => model.Address.ulkeID, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value="Türkiye" } })
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz il</label>
<select class="form-control col-md-12" name="Address.sehirID" id="il" required></select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz ilçe</label>
<select class="form-control col-md-12" name="Address.ilceID" id="ilce" disabled required>
<option>Bir İl Seçiniz</option>
</select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Açık adresiniz</label>
<div class="col-md-12">
#Html.EditorFor(model => model.Address.acikAdres, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Oluşturulma Tarihi</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.olusturulmaTarihi, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value=sqlFormat } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<div class="col-md-offset-2 col-md-12">
<input type="submit" value="Kaydol" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
Register Action:
[HttpPost]
public ActionResult Register(RegisterVM model)
{
tblKullanici user = null;
tblAdres address = null;
if(model != null)
{
db = new DatabaseContext();
user = model.User;
address = model.Address;
db.tblKullanici.Add(user);
db.tblAdres.Add(address);
db.SaveChanges();
if (db.SaveChanges() > 0)
{
Session["login"] = model.User;
return RedirectToAction("Index", "App");
}
}
ViewBag.Message = "Kayıt işlemi sırasında hata oluştu!";
return View(model);
}
jQuery
<script>
// ajax call to bring district and city info dynamically according to the city value
$(function () {
$.ajaxSetup({
type: "post",
url: "/User/IlIlce",// target
dataType: "json"
});
$.extend({
ilGetir: function () {
$.ajax({
//sending data
data: { "tip": "ilGetir" },
success: function (sonuc) {
//check result if ok then append it to selectlist
if (sonuc.ok) {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
$("body").append(optionhtml);
});
}
}
});
},
ilceGetir: function (cityID) {
$.ajax({
// then we get the districts with cityID
data: { "ilID": cityID, "tip": "ilceGetir" },
success: function (sonuc) {
// deleting records
$("#ilce option").remove();
if (sonuc.ok) {
// disabled to false
$("#ilce").prop("disabled", false);
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
}
}
});
}
});
// invoke ilGetir to get city values
$.ilGetir();
// on change in city value
$("#il").on("change", function () {
// we get the id of selected value
var cityID = $(this).val();
// and pass it to the ilceGetir function to get the districts
$.ilceGetir(cityID);
});
});
</script>
and the method that ajax call goes:
public JsonResult IlIlce(int? ilID, string tip)
{
db = new DatabaseContext();
List<SelectListItem> sonuc = new List<SelectListItem>();
bool isSuccessful = true;
try
{
switch (tip)
{
case "ilGetir":
// we assign the city values in db to sonuc(result) variable
foreach (var sehir in db.tblSehir.ToList())
{
sonuc.Add(new SelectListItem
{
Text = sehir.sehirAdi,
Value = sehir.sehirID.ToString()
});
}
break;
case "ilceGetir":
// we will fetch districts with sehirID(cityID)
foreach (var ilce in db.tblİlce.Where(il => il.bagliOlduguSehirID == ilID).ToList())
{
sonuc.Add(new SelectListItem
{
Text = ilce.ilceAdi,
Value = ilce.ilceID.ToString()
});
}
break;
default:
break;
}
}
catch (Exception e)
{
// if we encounter an error
isSuccessful = false;
sonuc = new List<SelectListItem>();
sonuc.Add(new SelectListItem
{
Text = e.Message,
Value = "Default"
});
}
// i return the results as json
return Json(new { ok = isSuccessful, text = sonuc });
}
ilce means: district
sehir/il both means: city
sifre: password
kullaniciAdi: username
telefon: phone number
ulke: country
ilGetir : fetch city
ilceGetir: fetch district
kullanici: user
adres: address
sonuc: result
tip: type
hello i am developing a web site using MVC in order to insert data into my data base i created method called chekout like below in my HomeController:
public ActionResult chekout()
{
return View(Tuple.Create<Commande,IEnumerable< Panier >, LoginViewModel> (new Commande(), db.Paniers.ToList(), new LoginViewModel()));
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult chekout([Bind(Include = "prenom,nom,Adresse,telephone,cart")] Commande commande)
{
if (ModelState.IsValid)
{
try
{
commande.Id_commande = db.Commandes.Max().Id_commande + 1;
var panier = from Panier in db.Paniers
select Panier;
var userEmail = this.User.Identity.Name;
panier = panier.Where(x => x.user.Contains(userEmail));
foreach (var item in panier)
{
commande.produit = item.Quantite + " X " + item.nom_produit;
commande.prix = int.Parse(item.prix) * item.Quantite;
commande.Email = userEmail;
db.Commandes.Add(commande);
db.SaveChanges();
}
return RedirectToAction("order_complete", "Home");
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
Console.ReadKey();
}
}
return RedirectToAction("chekout", "Home");
}
}
then i created the form in the view chekout like this :
#using (Html.BeginForm("chekout", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Item1.prenom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.prenom, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.prenom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.nom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.nom, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.nom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.Adresse, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.Adresse, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.Adresse, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.telephone, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.cart, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.cart, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.cart, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Commander" class="btn btn-primary" />
</div>
</div>
}
this is my page after i insert my data i click on commander it suppose to insert data into my database then move on the order_complete page but it id not it wipe up my data an redirect to the same page like this
but it did not work and i can not know why when i click on the button it take me back redirect to the same page without inserting data to my database
i would be grateful if anyone can help me
I've been trying to display my edit values in the editContact page. I ran out of ideas as to how I'm supposed to fix this.
Here's my controller for edit
[HttpGet]
public ActionResult editContact(int? id)
{
var databaseModel = new database();
if (id == null)
{
return RedirectToAction("Index");
}
IEnumerable<contact> contact = databaseModel.displayContact(id);
return View(contact);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult editContact(contact editModel, int id)
{
try
{
programEntities db = new programEntities();
var databaseModel = new database();
if (databaseModel.editContact(editModel, id))
{
ViewBag.AlertMsg = "Contact edited successfully";
return RedirectToAction("Index");
}
return View();
}
catch (Exception ex)
{
return View(ex);
}
}
In my model, I have this code that controls the database manipulation
public List<contact> displayContact(int? Id)
{
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand comObj = new SqlCommand("displayContact", conn))
{
comObj.CommandType = CommandType.StoredProcedure;
comObj.Parameters.Add(new SqlParameter("#contactId", Id));
conn.Open();
List<contact> contactList = new List<contact>();
SqlDataAdapter da = new SqlDataAdapter(comObj);
DataTable dt = new DataTable();
//conn.Open();
da.Fill(dt);
conn.Close();
contactList = (from DataRow dr in dt.Rows
select new contact()
{
contactId = Convert.ToInt32(dr["contactId"]),
establishmentType = Convert.ToString(dr["establishmentType"]),
ownerName = Convert.ToString(dr["ownerName"]),
address = Convert.ToString(dr["address"]),
city = Convert.ToString(dr["city"]),
region = Convert.ToString(dr["region"]),
mobileNumber = Convert.ToString(dr["mobileNumber"]),
phoneNumber = Convert.ToString(dr["phoneNumber"])
}).ToList();
return contactList;
}
}
My view markup:
#model directory.Models.contact
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>contact</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.contactId)
<div class="form-group">
#Html.LabelFor(model => model.establishmentType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.establishmentType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.establishmentType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ownerName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ownerName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ownerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.city, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.city, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.city, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.region, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.region, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.region, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.mobileNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.mobileNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.mobileNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.phoneNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.phoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.phoneNumber, "", new { #class = "text-danger" })
</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>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I tried creating a different query to display the edit values, but the exception says my dispayContact stored procedure does not exist even though it does. My other stored procedure works well except for this one.
Edit
So I fixed my stored procedure in SQL Server; it was named "dispayContact". Still the edit values won't display even after adding firstOrDefault() and then changing the declaration in my view from #model directory.Models.contact to #model IEnumerable<directory.Models.contact>
I think the issue is because you are returning a list
return View(contact);
where contact is IEnumerable<contact> and your view model is
#model directory.Models.contact
I guess your code should work once you return the model not list contain the model, in your case return FirstOrDefault() of your contact list
something like this
return View(contact.FirstOrDefault());
There are few issues with your function. You can use datareader which is much faster than data adopter. You also don't need to return a collection but just an object of your type:
Function to get object:
public contact displayContact(int? Id)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand comObj = new SqlCommand("displayContact", conn))
{
comObj.CommandType = CommandType.StoredProcedure;
comObj.Parameters.Add(new SqlParameter("#contactId", Id));
conn.Open();
using (SqlDataReader dr = comObj.ExecuteReader())
{
while (dr.Read())
{
return new contact
{
contactId = int.Parse(dr["contactId"].ToString()),
establishmentType = dr["establishmentType"].ToString(),
ownerName = dr["ownerName"].ToString(),
address = dr["address"].ToString(),
city = dr["city"].ToString(),
region = dr["region"].ToString(),
mobileNumber = dr["mobileNumber"].ToString(),
phoneNumber = dr["phoneNumber"].ToString()
};
}
}
}
conn.Close();
}
return null;
}
Controller Action:
public ActionResult editContact(int? id)
{
var databaseModel = new database();
if (id == null)
{
return RedirectToAction("Index");
}
var contact = databaseModel.displayContact(id);
return View(contact);
}
I have a view which gets username and password and needs to pass it to the Database. I can pass the username but not the password.
View:
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "label-control" })
#Html.PasswordFor(m => m.UserName, new { #class = "form-control", autofocus = "", value = "Text" })
#Html.ValidationMessageFor(m => m.UserName, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "label-control" })
#Html.TextBoxFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "alert-danger" })
</div>
Controller:
public ActionResult EditUserSubmit(string UserName, string Password, string ProcessType)
{
string process;
string name = Url.RequestContext.RouteData.Values["id"].ToString();
process = (ProcessType == "Processed") ? "P" : "B";
DB.Entities.user users = db.users.Where(m => m.username == name).FirstOrDefault();
users.password = Password;
users.processtype = process;
db.SaveChanges();
return RedirectToAction("Manager");
}
UPDATE
This is the whole View
#model NV.Tax.SST.Gateway.MVC.Models.AdministrationModel
#{string name = Url.RequestContext.RouteData.Values["id"].ToString();}
<div class="x-form-wrapper">
<div class="x-form-title">
<h3><strong>User Detail for <b>#Url.RequestContext.RouteData.Values["id"]</b></strong></h3>
</div>
<div class="x-form-body">
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "label-control" })
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", autofocus = "", value = "Text" })
#Html.ValidationMessageFor(m => m.UserName, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "label-control" })
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.ProcessType, new { #class = "label-control" })
#Html.DropDownListFor(m => m.ProcessType, new[]{
new SelectListItem { Text = "Processed", Value = "Processed" },
new SelectListItem { Text = "Both", Value = "Both" }
}, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProcessType, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
Save
#Html.ActionLink("Cancel", "Manager", "Administration", null, new { #class = "btn btn-lg btn-default" })
</div>
</div>
</div>
#{
string password = "";
var entity = new NV.Tax.SST.Gateway.DB.Entities.sstpEntities();
var data = from db in entity.users
where db.username == name
select db;
foreach(var item in data)
{
password = item.password;
<script>document.getElementById("Password").defaultValue = "#password"</script>
if (item.processtype == "B")
{
<script>document.getElementById("ProcessType").value = "Both"</script>
}
else
{
<script>document.getElementById("ProcessType").value = "Processed"</script>
}
}
}
Since you're creating the password textbox like this
#Html.TextBoxFor(m => m.Password, new { #class = "form-control" })
It's clear that you're using a view model class that has UserName and Password property. I'd guess that it also has ProcessType property. Since you have the following syntax at the top of your view
#model NV.Tax.SST.Gateway.MVC.Models.AdministrationModel
You can use NV.Tax.SST.Gateway.MVC.Models.AdministrationModel as the parameter of your controller action method as below
public ActionResult EditUserSubmit(NV.Tax.SST.Gateway.MVC.Models.AdministrationModel model)
{
string process;
string name = Url.RequestContext.RouteData.Values["id"].ToString();
process = (model.ProcessType == "Processed") ? "P" : "B";
DB.Entities.user users = db.users.Where(m => m.username == name).FirstOrDefault();
users.password = model.Password;
users.processtype = process;
db.SaveChanges();
return RedirectToAction("Manager");
}
The value of model.Password will be what you enter in the password textbox.
EDIT
After looking at the whole view code, this is where you're wrong
Save
You can't submit the page using an anchor tag and without <form> tag. You need to have a <form> tag and a submit button inside it. The <form> tag can be generated using Html.BeginForm helper method. Change your view code to below
#model NV.Tax.SST.Gateway.MVC.Models.AdministrationModel
#{string name = Url.RequestContext.RouteData.Values["id"].ToString();}
<div class="x-form-wrapper">
<div class="x-form-title">
<h3><strong>User Detail for <b>#Url.RequestContext.RouteData.Values["id"]</b></strong></h3>
</div>
<div class="x-form-body">
#using (Html.BeginForm("EditUserSubmit", "Administration"))
{
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "label-control" })
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", autofocus = "", value = "Text" })
#Html.ValidationMessageFor(m => m.UserName, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "label-control" })
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.ProcessType, new { #class = "label-control" })
#Html.DropDownListFor(m => m.ProcessType, new[]{
new SelectListItem { Text = "Processed", Value = "Processed" },
new SelectListItem { Text = "Both", Value = "Both" }
}, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProcessType, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
<button type="submit" class="btn btn-lg btn-primary">Save</button>
#Html.ActionLink("Cancel", "Manager", "Administration", null, new { #class = "btn btn-lg btn-default" })
</div>
}
</div>
</div>
#{
string password = "";
var entity = new NV.Tax.SST.Gateway.DB.Entities.sstpEntities();
var data = from db in entity.users
where db.username == name
select db;
foreach(var item in data)
{
password = item.password;
<script>document.getElementById("Password").defaultValue = "#password"</script>
if (item.processtype == "B")
{
<script>document.getElementById("ProcessType").value = "Both"</script>
}
else
{
<script>document.getElementById("ProcessType").value = "Processed"</script>
}
}
}
You should also add [HttpPost] attribute and change your controller action method as below
[HttpPost]
public ActionResult EditUserSubmit(NV.Tax.SST.Gateway.MVC.Models.AdministrationModel model)
{
string process = (model.ProcessType == "Processed") ? "P" : "B";
DB.Entities.user users = db.users.Where(m => m.username == model.UserName).FirstOrDefault();
users.password = model.Password;
users.processtype = process;
db.SaveChanges();
return RedirectToAction("Manager");
}
I have ASP.net-mvc5 website. I need to allow user update/ edit two emergency contact details. To achieve that I am sending "list myModel" to razor view and in view I got two #html.beginform. I have List because I know I always have two record. I am printing value from list via index 0 for record 1 and 1 for record 2. Jquery Ajax function used to post data back to controller.
Now form 1 for emergency contact detail 1 is working fine but form 2 for 2nd emergency contact detail posting null values to controller. I have commet form1 and tried to submit form2 but still null values. I am not sure why this happening.
Controller
[Authorize]
[HttpGet]
public ActionResult EditEmergencyContact()
{
int _studentEntityID = 0;
_studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());
List<EmergencyContact> _emergencyContactModel = new List<EmergencyContact>();
_emergencyContactModel = _studentProfileServices.GetEmergencyContactByStudentID(_studentEntityID);
return PartialView("EditEmergencyContact_Partial", _emergencyContactModel);
}
[Authorize]
[HttpPost]
public ActionResult EditEmergencyContact(List<EmergencyContact> _emergencyContactModel)
{
try
{
if (_emergencyContactModel!=null && _emergencyContactModel.Count()>0)
{
if (ModelState.IsValid)
{
int _entityID = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[0].EmergencyContactID,
StudentID = _emergencyContactModel[0].StudentID,
NameOfContact = _emergencyContactModel[0].NameOfContact,
Relationship = _emergencyContactModel[0].Relationship,
Telephone = _emergencyContactModel[0].Telephone,
Mobile = _emergencyContactModel[0].Mobile,
Address = _emergencyContactModel[0].Address
});
if (_entityID != 0)
{
return Json(new { Response = "Success" });
}
else
{
return Json(new { Response = "Error" });
}
}
else
{
return Json(new { Response = "Invalid Entry" });
}
}
else
{
return Json(new { Response = "Error! In Updating Record" });
}
}
catch (DataException ex)
{
ModelState.AddModelError("", "Unable To Edit Emergency Contact" + ex);
}
return RedirectToAction("MyProfile", "StudentProfile");
}
View
#using (Html.BeginForm("EditEmergencyContact", "StudentProfile", FormMethod.Post, new { id = "EditNo2EmergencyContactForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Emergency Contact 2</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model[1].EmergencyContactID)
<div class="form-group">
#Html.LabelFor(model => model[1].StudentID, "StudentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].StudentID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].StudentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].NameOfContact, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].NameOfContact, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].NameOfContact, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Relationship, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Relationship, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Relationship, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Telephone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Address, "", new { #class = "text-danger" })
</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>
}
Jquery Function
$('#EditNo2EmergencyContactForm').submit(function (e) {
e.preventDefault();
var formURL = $(this).attr("action");
alert($(this).serialize());
$.ajax({
url: formURL,
type: "POST",
data: $(this).serialize()
}).done(function (data, textStatus, jqXHR) {
if (data.Response == "Success") {
$(this).MyMessageDialog({
_messageBlockID: "_StatusMessage",
_messageContent: "Record Been Updated Successfully",
_messageBlockWidth: "300px"
});
$('div#_StatusMessage').on('dialogclose', function (event) {
window.location = "/StudentProfile/MyProfile";
});
}
else {
$(this).MyMessageDialog({
_messageBlockID: "_StatusMessage",
_messageContent: "<div class='errorMessage'>" + data.Response + "</div>",
_messageBlockWidth: "300px"
});
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$(this).MyMessageDialog({
_messageBlockID: "_StatusMessage",
_messageContent: "<div class='errorMessage'> Error In Updating Record! " + textStatus + " " + errorThrown + " "+jqXHR.status +"</div>",
_messageBlockWidth: "350px"
});
$('div#_StatusMessage').on('dialogclose', function (event) {
window.location = "/StudentProfile/MyProfile";
});
});
});
For Form 1: this one works
#using (Html.BeginForm("EditEmergencyContact", "StudentProfile", FormMethod.Post, new { id = "EditNo1EmergencyContactForm" }))
..............
$('#EditNo1EmergencyContactForm').submit(function (e) {
You are using same controller post action for different forms.
Your action update model (list of entities) only entity present on first position.
Your models has a list of [entity0, entity1] but in form view you remove entity0 because you are binding only one entity1 from model having list.
Here you have 2 approaches:
Make post controller action more generic
public ActionResult EditEmergencyContact (List<EmergencyContact> _emergencyContactModel)
{
try
{
if (_emergencyContactModel != null && _emergencyContactModel.Count() > 0)
{
if (ModelState.IsValid)
{
bool validation = true;
for (int i = 1; i < _emergencyContactModel.Count(); i++)
{
if (_emergencyContactModel[i].EmergencyContactID != null)
{
int _entityID = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[i].EmergencyContactID,
StudentID = _emergencyContactModel[i].StudentID,
NameOfContact = _emergencyContactModel[i].NameOfContact,
Relationship = _emergencyContactModel[i].Relationship,
Telephone = _emergencyContactModel[i].Telephone,
Mobile = _emergencyContactModel[i].Mobile,
Address = _emergencyContactModel[i].Address
});
if (_entityID == 0)
{
validation = false;
break;
}
}
}
if (validation)
{
return Json(new { Response = "Success" });
}
else
{
return Json(new { Response = "Error" });
}
}
else
{
return Json(new { Response = "Invalid Entry" });
}
}
else
{
return Json(new { Response = "Error! In Updating Record" });
}
}
catch (DataException ex)
{
ModelState.AddModelError("", "Unable To Edit Emergency Contact" + ex);
}
return RedirectToAction("MyProfile", "StudentProfile");
}
Option 2, do not pass model empty entities to controller, hide inside the form the values:
#using (Html.BeginForm("EditEmergencyContact", "StudentProfile", FormMethod.Post, new { id = "EditNo2EmergencyContactForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Emergency Contact 2</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#* here you pas List 0 model recieved value and viceversa if you edit model[0]*#
#Html.HiddenFor(model => model[0].EmergencyContactID)
#Html.HiddenFor(model => model[0].StudentID)
#Html.HiddenFor(model => model[0].NameOfContact)
#Html.HiddenFor(model => model[0].Relationship)
#Html.HiddenFor(model => model[0].Telephone)
#Html.HiddenFor(model => model[0].Mobile)
#Html.HiddenFor(model => model[0].Address)
#Html.HiddenFor(model => model[0].Address)
#Html.HiddenFor(model => model[1].EmergencyContactID)
<div class="form-group">
#Html.LabelFor(model => model[1].StudentID, "StudentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].StudentID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].StudentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].NameOfContact, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].NameOfContact, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].NameOfContact, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Relationship, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Relationship, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Relationship, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Telephone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Address, "", new { #class = "text-danger" })
</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>
}
the controller where you update both entities from list :
int _entityID_0 = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[0].EmergencyContactID,
StudentID = _emergencyContactModel[0].StudentID,
NameOfContact = _emergencyContactModel[0].NameOfContact,
Relationship = _emergencyContactModel[0].Relationship,
Telephone = _emergencyContactModel[0].Telephone,
Mobile = _emergencyContactModel[0].Mobile,
Address = _emergencyContactModel[0].Address
});
int _entityID_1 = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[1].EmergencyContactID,
StudentID = _emergencyContactModel[1].StudentID,
NameOfContact = _emergencyContactModel[1].NameOfContact,
Relationship = _emergencyContactModel[1].Relationship,
Telephone = _emergencyContactModel[1].Telephone,
Mobile = _emergencyContactModel[1].Mobile,
Address = _emergencyContactModel[1].Address
});
if (_entityID_0 != 0 && _entityID_1 != 0)
{
return Json(new { Response = "Success" });
}
else
{
return Json(new { Response = "Error" });
}
Your approach is very bad, you should update address one by one not a complex list of address.