Display values in edit - c#

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);
}

Related

how can i make Html. Begin Form() work using MVC

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

Edit/Update in Asp.net mvc

When I click OK, it doesn't update the record but rather redirects to the other page without the updated having been shown. What is happening now is that it would return blank; not even showing the record that was entered at initial stage. What I was trying to achieve is when the user clicks OK, redirect to the page with the updated record.
Form
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Issue</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<fieldset>
<div class="form-horizontal">
#Html.LabelFor(model => model.item.itemNumber, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.TextBoxFor(model => model.item.itemNumber, null, new { #id = "itemNumber", #class = "form-control", #readonly = "readonly", })
#Html.ValidationMessageFor(model => model.item.itemNumber, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.expense_acccount, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.item.expense_account.index, new SelectList(Model.accountlist, "Value", "Text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.expense_acccount, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.item.price, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.TextBoxFor(model => model.item.price, new { #id = "price", #class = "form-control", #readonly = "readonly", })
#Html.ValidationMessageFor(model => model.item.price, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.item.quantity, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.item.quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantity, "", new { #class = "text-danger" })
<input type="submit" value="OK" name="OK" class="btn btn-default" />
<input type="button" value="Cancel" name="Cancel" onclick="location.href='#Url.Action("IssueItem","Issue")' " class="btn btn-default" />
Controller
public ActionResult Edit(int id)
{
getIssue.item = getIssue.items[id - 1]; //Returns the requested item for editing
return View(getIssue);
}
public ActionResult Edit(Issue issue)
{
int indx = issue.item.lineNum - 1;
getIssue.items[indx] = issue.item;
return RedirectToAction("IssueItem");
}
public ActionResult IssueItem()
{
Session.Clear();
IssueDAO dbData = new IssueDAO();
getIssue.docNumber = string.Concat("IS", DateTime.Now.ToString("yymmddhhmmss"));
getIssue.docType = "Issue"; getIssue.inventory_acccount = 5520; ViewBag.StoresReps = dbData.SelectEmployeesByDept("Stores");
getIssue.item = new Item();
return View(getIssue);
}
private Issue getIssue {
get
{
Issue issue = (Issue)Session["Issue"];
if (issue == null) { issue = new Issue();
Session["Issue"] = issue; } return issue;
}
}

Error while posting dropdown [duplicate]

This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 5 years ago.
I'm getting the following error:
There is no ViewData item of type 'IEnumerable' that has the key 'Category'.
Line 34:div class="form-group">
Line 35:
Line 36:#Html.DropDownList("Category", (IEnumerable)ViewBag.DropdownValues,"Select Category", new { #class = "form-control" })
Line 37:
Line 38:
Model:
public class CateogryList
{
public string categoryValues { get; set; }
public IEnumerable<SelectListItem> categoryValuesList { get; set; }
}
Controller:
public ActionResult CreateService()
{
CateogryList cate = new CateogryList();
ServiceProviderRepository values = new ServiceProviderRepository();
List<string> details = new List<string>(values.displayCateogry());
var types = new List<SelectListItem>();
int counter = 0;
foreach (string val in details)
{
types.Add(new SelectListItem() { Text = val, Value = Convert.ToString(counter) });
counter += 1;
}
ViewBag.DropdownValues = new SelectList(details, cate.categoryValues, "");
return View();
}
[HttpPost]
public ActionResult CreateService(ServicesViewModel addService, FormCollection form)
{
ViewData["SelectedItem"] = form["Category"].ToString();
// ViewData["SelectedItem"] = HttpContext.Request.QueryString["Category"];
return View();
}
Servicerepository:
public class ServiceProviderRepository
{
private SqlConnection con;
/*
* To Handle Database connection related activities
* #parameter: No parameter
*/
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["Event_Database"].ToString();
con = new SqlConnection(constr);
}
public List<string> displayCateogry()
{
List<string> list = new List<string>();
connection();
string SQLquery = "Select Category from category";
SqlCommand com1 = new SqlCommand(SQLquery, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com1);
DataTable dt = new DataTable();
da.Fill(dt);
foreach(DataRow row in dt.Rows)
{
list.Add(row.Field<string>(0));
}
return list;
}
}
View:
#model Event_Planner_MVC_Application.Models.ServicesViewModel
#{
ViewBag.Title = "CreateService";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create Service</h2>
#using (Html.BeginForm("CreateService", "ServiceProvider", FormMethod.Post))
{
#Html.AntiForgeryToken()
<h3>You have Selected: #ViewData["SelectedItem"]</h3>
<div class="form-horizontal">
<h4>ServicesViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new {
#class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes
= new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new {
#class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Cost, htmlAttributes: new { #class =
"control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Cost, new { htmlAttributes = new
{ #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Cost, "", new { #class
= "text-danger" })
</div>
</div>
<div class="form-group">
<div class="form-group">
#Html.DropDownList("Category",
(IEnumerable<SelectListItem>)ViewBag.DropdownValues,"Select Category", new {
#class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
In your Controller change ViewBag.DropdownValues to ViewBag.Category and in View
Controller
ViewBag.Category= new SelectList(details, cate.categoryValues, "");
View
#Html.DropDownList("Category",
(IEnumerable<SelectListItem>)ViewBag.Category,"Select Category", new {
#class = "form-control" })

Foreign Key Reference to IdentityUser Shows NULL Values (EF6/ASP.NET MVC 5)

I am trying to figure out why my model table's UserId column which references the primary key, "Id" of my AspNetUsers table (IdentityUser class in IdentityModel) is showing only NULL values when I 'Create()' an entry.
Here is the code for my two Create(), ActionResult methods in my controller class:
[Authorize]
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname");
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "ID,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense)
{
if (ModelState.IsValid)
{
expense.UserId = HttpContext.Current.User.Identity.Name;
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId);
return View(expense);
}
Here is the code for my Create view:
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
DateTime today = DateTime.Today;
string formattedDate = today.ToString("MM/dd/yyyy");
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Expense</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.UserId, htmlAttributes: new { #Value = user, #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateSubmitted, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateSubmitted, new { htmlAttributes = new { #Value = formattedDate, #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateSubmitted, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExpenseDate, htmlAttributes: new { #Value = #formattedDate, #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExpenseDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ExpenseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Category, new SelectList(
new List<String>{
"Meals & Entertainment",
"Home Office",
"Travel",
"Phone",
"Auto - Mileage",
"Auto - Gas",
"Auto - Lease",
"Association Dues",
"Insurance Premium",
"Capital Assets",
"Trade Show & Promo",
"Pan Experience",
"Other"
}), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mileage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mileage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mileage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MileageRate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MileageRate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MileageRate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GrossAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GrossAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GrossAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TaxAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TaxAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TaxAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NetAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NetAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NetAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section scripts {
<script type="text/javascript">
var province = 'bc';
var grossAmount = document.getElementById('GrossAmount').value;
$(function () {
$('#ExpenseDate').datetimepicker({
defaultDate: '#formattedDate',
format: 'L',
showClose: true,
showClear: true,
toolbarPlacement: 'top'
});
});
$('#DateSubmitted').prop('readonly', true);
$('#Mileage').prop('disabled', true);
$('#MileageRate').prop('disabled', true);
$(function ()
{
$('#Category').on('change',function()
{
if ($(this).val() == 'Auto - Mileage')
{
$('#Mileage').prop('disabled', false);
$('#MileageRate').prop('disabled', false);
}
else
{
$('#Mileage').prop('disabled', true);
$('#MileageRate').prop('disabled', true);
}
}
)
})
</script>
}
If you would like to take a look at my model classes, you can go this post:
How To Restrict User Entries Only to that Sepcific User in EF 6/ASP.NET MVC 5
UPDATE:
Thanks to Steve Greene for putting me on the right track and for helping me to update my Create() method to this:
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname");
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "ExpenseId,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense)
{
if (ModelState.IsValid)
{
expense.UserId = System.Web.HttpContext.Current.User.Identity.Name;
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId);
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
Response.Write(error);
}
}
Response.End();
return View(expense);
}
I don't get any major errors now, however, now ModelState.IsValid is returning False and the data I enter into Create.cshtml isn't being submitted.
I added a piece of code in the Create() method to catch the ModelState.Errors and it prints the error: System.Web.Mvc.ModelError.
I've also set a breakpoint before Create() and when I check the value of UserId, I get "null."
LAST UPDATE:
I've added a field for UserId to the Create.cshtml view and now I get the error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Expenses_dbo.AspNetUsers_ApplicationUser_Id". The conflict occurred in database "PacificPetExpenses", table "dbo.AspNetUsers", column 'Id'.
To fix this, I modified something in my controller (please see my answer below).
Thank you.
If you are not using the UserId in the view, just set it before you add:
if (ModelState.IsValid)
{
expense.UserId = HttpContext.Current.User.Identity.Name; // or whatever
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
Another common pattern is to add a hidden field for the UserId:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.UserId) <-- now it will post back
...
If you want to have a drop down list of users, do this:
[Authorize]
public ActionResult Create()
{
ViewBag.UserList = new SelectList(db.Users, "Id", "Fullname");
return View();
}
Then in your view add a drop down list of users:
<div class="form-group">
#Html.LabelFor(model => model.UserId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.UserId, Model.UserList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
Inside of the Create() method inside of my controller, I had the line:
expense.UserId = HttpContext.Current.User.Identity.Name;
I set up a break point and as breakpoint was on the line, it showed the correct UserId; however, after the line had executed, it showed the user's email address.
To fix this I tried changing the line above to:
expense.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
and expenses were both being submitted with no errors and displaying in the view where it was supposed to show the list of expenses submitted by the user!

html.beginForm post null value for List<strongly typed> to controller via jQuery Ajax function in ASP>NET-MVC5

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.

Categories

Resources