Passing value from a viewbag to a view - c#

I'm trying to pass value from a view bag to the view create.
Controller
public ActionResult Create()
{
ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");
if (ViewBag.BanhoTosaId.SelectedValue != null)
{
BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
decimal valorSoma = BT.Valor + 10;
ViewBag.Total = valorSoma;
}
else
{
ViewBag.Total = 0;
}
return View();
}
view
<div class="form-group">
#Html.LabelFor(model => model.Total, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Total, new { htmlAttributes = new { #class = "form-control", value = "#ViewBag.Total" } })
#Html.ValidationMessageFor(model => model.Total, "", new { #class = "text-danger" })
</div>
</div>
In case BT will get the value in the BanhoTosa table and add 10, and then will return the value of the sum in the viewbag.Total.
But in view the #Html.EditorFor is receiving nothing
How can i do for the editorfor receive the value from the viewbag.total?
Thank's Guy's

Related

ASP.Net MVC sending new Object to view fills some fields with bad data

I asked a question yesterday about how to fix a sudden and unexpected "Object not set to an instance of an object" error. The only real answer I got was to pass a new instance of the object to the view like this:
// GET: WC_Inbox/Create
public ActionResult Create(int? id)
{
System.Diagnostics.Debug.WriteLine("Employee ID was: " + id);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return HttpNotFound();
}
string fullName = employee.First_Name + " " + employee.Last_Name;
System.Diagnostics.Debug.WriteLine("Employee full name: " + fullName);
ViewBag.EmployeeID = id;
ViewBag.Name = fullName;
ViewBag.Status = "Pending";
return View(new WC_Inbox());
}
With the primary line in question being here: return View(new WC_Inbox());
This worked, however it has created further issues. Now on my create page I am given some incorrect data in some fields
The fields Org Number, Hire Date, Work Schedule, and Injury date should not show those values. Those are incorrect and will be very confusing to the mostly elderly client bass the app is intended for. I would like for the placeholder values to show up there rather than this incorrect data.
This is the code from the Create view for those fields:
<div class="form-group">
#Html.LabelFor(model => model.Org_Number, "Org Number", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Org_Number, new { htmlAttributes = new { #class = "form-control", placeholder = "0025" } })
#Html.ValidationMessageFor(model => model.Org_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hire_Date, "Hire Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { #class = "form-control", placeholder = "8/3/2021" } })
#Html.ValidationMessageFor(model => model.Hire_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Job_Title, "Job Title", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Job_Title, new { htmlAttributes = new { #class = "form-control", placeholder = "Programmer Analyst" } })
#Html.ValidationMessageFor(model => model.Job_Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Work_Schedule, "Work Schedule", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Work_Schedule, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Work_Schedule, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Injury_Date, "Injury Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Injury_Date, new { htmlAttributes = new { #class = "form-control", placeholder = "8/14/2021" } })
#Html.ValidationMessageFor(model => model.Injury_Date, "", new { #class = "text-danger" })
</div>
</div>
How can I get rid of that bad data and use the placeholder values I assigned instead?
PS: Work Schedule should simply be blank. There is no placeholder value.
The issue is that you are passing a default object to the strongly-typed view. On the line:
return View(new WC_Inbox());
you have not done anything to initialize the properties/values on the WC_Inbox object. This means that all the values will be the default value (0 for int, null for string, the minimum date time for DateTime, etc.) It is those default values that you are seeing on your view. If you would like blank default values, you just have to update the WC_Inbox class to support nullable types. This works because null values display as blanks, so your placeholder text will show up. For example, it worked as expected for Job_Title since Job_Title is a string and its default value is null which is then displayed as a blank by EditorFor which allows the placeholder text to display. Hopefully that makes sense - it is simple, but verbose to explain.
If your WC_Inbox class can allow for nullable values, update it and then your placeholders would work. So the class now looks like:
class WC_Inbox
{
public int? Org_Number {get; set;}
public DateTime? Hire_Date { get; set;}
public string Job_Title {get; set;} // string is nullable already
public DateTime? Work_Schedule {get; set;}
public DateTime? Injury_Date {get; set;}
}
If you update the definition of WC_Inbox then the code as you have it will work.

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

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

How to multiply values of two textboxes in Asp.net MVC

I have 3 textboxes, 1st for Quantity, 2nd for Price and 3rd for Total Price.
<div class="form-group">
#Html.LabelFor(model => model.quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.quantity, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.price, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.totalprice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.totalprice, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.totalprice, "", new { #class = "text-danger" })
</div>
and here is the controller:
[HttpPost]
public ActionResult Add(Model model)
{
obj.Quantity = model.quantity;
obj.Price = model.price;
obj.TotalPrice = model.totalprice
db.Details.Add(obj);
db.SaveChanges();
return RedirectToAction("");
}
now I want to multiply values of 1st and 2nd textboxes and show them in 3rd textbox. For example if users enter 5 in 1st textbox and 100 in 2nd textbox then it automatically shows 500 in 3rd textbox and if users changes value of 1st or 2nd textbox then value of 3rd textbox should also change accordingly.
Thanks.
You can listen to the keyup event of the textboxes in javascript, read the value and do the multiplication and set the resulting value to the third textbox.
Assuming your have jQuery library included in your page.
$(function(){
$("#quantity,#price").keyup(function(e){
var q=$("#quantity").val();
var p=$("#price").val();
var result="";
if(q!=="" && p!=="" && $.isNumeric(q) && $.isNumeric(p))
{
result = parseFloat(q)*parseFloat(p);
}
$("#totalPrice").val(result);
});
});
Here is a working jsbin sample.
You can use this:
[HttpPost]
public ActionResult Add(Model model)
{
obj.Quantity = model.quantity;
obj.Price = model.price;
obj.TotalPrice = model.totalprice
model.totalprice = model.quanity * model.price
db.Details.Add(obj);
db.SaveChanges();
return RedirectToAction("");
}
Hope it helps. I used it in my application and it does the right thing.

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