Error while posting dropdown [duplicate] - c#

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

Related

Select name based on ID with ASP.NET MVC

I create a new form and I want view name based on id in another table, but the id can't view in the dropdown list:
This is the view:
<div class="form-group">
<label class="control-label col-md-2">ID Operator</label>
<div class="col-md-10">
#Html.DropDownList("idOp", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.idOp, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Name</label>
<div class="control-label col-md-10">
#Html.EditorFor(model => model.tbl_operator.nama, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.tbl_operator.nama , "", new { #class = "text-danger" })
</div>
</div>
This is the controller :
public ActionResult Create()
{
ViewBag.idEx = new SelectList(db.tbl_exercises, "idEx");
ViewBag.idOp = new SelectList(db.tbl_operator, "idOp");
return View();
}
Maybe I'm missing the code.
You need choose what field is Name, Value for SelectList like
ViewBag.idEx = new SelectList(tbl_exercises, "Value", "Name");
I made an example base on your code
var tbl_exercises = new List<exercises>
{
new exercises
{
Name = "Name 1",
Value = 10
},
new exercises
{
Name = "Name 2",
Value = 11
}
};
ViewBag.idEx = new SelectList(tbl_exercises, "Value", "Name");
SelectList is defined as
public SelectList(IEnumerable items, string dataValueField, string dataTextField);
In your controller, try to use
ViewBag.idOp = new SelectList(db.tbl_operator, "idOp","idOp");

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

Display values in edit

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

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.

MVC5 repository and unitofwork pattern

I am trying to implement a search method: getCompte using account number and as a parametre but i could'nt get the response view!! i don't know where is the error
Form:
#using (Html.BeginForm("SearchCompte", "Compte", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("NumCompte", new { #class = "col-md-2 control-label" })
<div class="col-md-3">
#Html.TextBox("NumCompte","", new { #class = "form-control", #placeholder = "N° Compte" })
#Html.ValidationMessage("NumCompte", "", new { #class = "text-danger" })
</div>
#Html.Label("CléRIB", new { #class = "col-md-1 control-label" })
<div class="col-md-2">
#Html.TextBox("CléRIB", "",new { #class = "form-control", #placeholder = "Clé" })
#Html.ValidationMessage("CléRIB", "", new { #class = "text-danger" })
</div>
<div class=" col-md-2">
<input type="submit" name="Search1" value="Search" class="btn btn-primary" />
</div>
</div>
controller:
[HttpGet]
public ActionResult SearchCompte()
{
//var Compte = new Compte();
//var cp = service.GetComptes();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SearchCompte(string NumCompte,string CléRIB)
{
try
{
long num = Convert.ToInt64(NumCompte);
var cp = service.GetCompte(num);
return View(cp);
}
catch (Exception)
{
ViewBag.Message = " The account doesn't exist";
return View();
}
}

Categories

Resources