Textarea won't save to database using jQuery - c#

I'm trying to dynamically add form fields using jQuery and save the input in my database. All of the fields are saving to the database just fine except for the textarea. I'm not sure what the issue is.
View
#model DailyTaskList.Models.DTL_Tasks
#{
var db = new DailyTaskList.Models.DailyTaskListEntities();
var options = db.DTL_UserOptions.Where(u => u.UserProfile.UserId == WebMatrix.WebData.WebSecurity.CurrentUserId);
var priority = db.DTL_Tasks.Select(p => p.Priority).FirstOrDefault();
var customerNames = db.DTL_Customers.Select(c => c.CustomerName);
var userSelectedTasks = options.Select(o => o.DTL_TaskTypes);
SelectList userSelectedTasksList = new SelectList(userSelectedTasks);
var priorityListItems = new SelectListItem[] {
new SelectListItem(){ Text="", Value="0" },
new SelectListItem(){ Text="Low", Value="1" },
new SelectListItem(){ Text="Medium", Value="2" },
new SelectListItem(){ Text="High", Value="3" },
new SelectListItem(){ Text="Highest", Value="4" }
};
using (Html.BeginForm("Index", "NewTask", FormMethod.Post, new { id = "new-task-form" })) {
#Html.ValidationSummary(true)
// Original form fields
<div class="new-task-form-wrapper">
<div class="form-group">
<label>Customer:</label>
#Html.DropDownListFor(model => model.CustomerId, new SelectList(db.DTL_Customers, "CustomerId", "CustomerName"), new { #class = "form-control", id = "Customer_0" })
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-10">
<label>Activity:</label>
#Html.DropDownListFor(model => model.TaskTypeId, new SelectList(userSelectedTasks, "TaskTypeId", "TaskName"), new { #class = "form-control", id = "Activity_0" })
</div>
<div class="col-sm-2">
<label>Priority:</label>
#Html.DropDownListFor(model => model.Priority, priorityListItems, new { #class = "form-control", id = "Priority_0" })
</div>
</div>
</div>
<div class="form-group">
<label>Title:</label>
#Html.TextBoxFor(model => model.TaskTitle, new { #class = "form-control", id = "Title_0" })
</div>
<div class="form-group description">
<label>Description:</label>
#Html.TextAreaFor(model => model.TaskDescription, new { #class = "form-control", id = "Description_0" })
</div>
</div>
// Additional form fields
<div id="additional-form-fields_0" class="hide new-task-form-wrapper">
<div class="form-group">
<label>Customer:</label>
#Html.DropDownListFor(model => model.CustomerId, new SelectList(db.DTL_Customers, "CustomerId", "CustomerName"), new { #class = "form-control", id = "Customer_1" })
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-10">
<label>Activity:</label>
#Html.DropDownListFor(model => model.TaskTypeId, new SelectList(userSelectedTasks, "TaskTypeId", "TaskName"), new { #class = "form-control", id = "Activity_1" })
</div>
<div class="col-sm-2">
<label>Priority:</label>
#Html.DropDownListFor(model => model.Priority, priorityListItems, new { #class = "form-control", id = "Priority_1" })
</div>
</div>
</div>
<div class="form-group">
<label>Title:</label>
#Html.TextBoxFor(model => model.TaskTitle, new { #class = "form-control", id = "Title_1" })
</div>
<div class="form-group description">
<label>Description:</label>
#Html.TextAreaFor(model => model.TaskDescription, new { #class = "form-control", id = "Description_1" })
</div>
</div>
// Form controls
<div class="form-group">
<button type="submit" class="btn btn-default" value="Create">Submit</button>
<div class="btn btn-default" id="addnew">+</div>
#*<div class="btn btn-default" id="remove">-</div>*#
</div>
}
}
Script
$(document).ready(function () {
CKEDITOR.replace('Description_0');
var counter = 0;
var additionalFormFields = $("#additional-form-fields_" + String(counter));
var customerInput = $("#Customer_1"),
activityInput = $("#Activity_1"),
priorityInput = $("#Priority_1"),
titleInput = $("#Title_1"),
descriptionInput = $("#Description_1");
$('#addnew').click(function () {
if (counter == 0) {
additionalFormFields.removeClass("hide");
}
else {
var newFormFields = additionalFormFields.clone();
additionalFormFields.after(newFormFields);
}
additionalFormFields.attr("id", "additional-form-fields_" + String(counter));
customerInput.attr("id", "Customer_" + String(counter + 1));
customerInput.attr("name", "CustomerId_" + String(counter));
activityInput.attr("id", "Activity_" + String(counter + 1));
activityInput.attr("name", "TaskTypeId_" + String(counter));
priorityInput.attr("id", "Priority_" + String(counter + 1));
priorityInput.attr("name", "Priority_" + String(counter));
titleInput.attr("id", "Title_" + String(counter + 1));
titleInput.attr("name", "TaskTitle_" + String(counter));
descriptionInput.attr("id", "Description_" + String(counter + 1));
descriptionInput.attr("name", "DescriptionId_" + String(counter));
counter++;
return false;
});
$('#new-task-form').on('submit', function (e) {
e.preventDefault();
var data = [];
$.each($(".new-task-form-wrapper"), function (i, o) {
data.push({
CustomerId: $(this).find("select[name^='CustomerId']").val(),
TaskTypeId: $(this).find("select[name^='TaskTypeId']").val(),
Priority: $(this).find("select[name^='Priority']").val(),
TaskTitle: $(this).find("input[name^='TaskTitle']").val(),
TaskDescription: $(this).find("textarea[name^='DescriptionId']").val()
});
});
$.ajax({
url: 'NewTask/Index',
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data)
});
});
});

Well, your text area's name is TaskDescription so the more appropriate selector would be:
TaskDescription: $(this).find("textarea[name^='TaskDescription']").val()

Related

The record is getting inserted or updated in datatable after page refresh and also notify.js popup is not working after insert/update in ASP.NET MVC

I'm new to ASP.NET MVC and I have created CRUD operations using datatables.
I need some help for notify.js popup is not working after inserting and updating data and also the record is getting inserted or updated in datatable after page refresh in ASP.NET MVC.
This is my markup and code:
AddOrEdit.cshtml:
#model Asp.NETMVCCRUD.Models.Employee
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Employee", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
#Html.HiddenFor(model => model.EmployeeID)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Position, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Position, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Position)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Office, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Office, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Office)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Age)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salary, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Salary, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salary)
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-warning" />
</div>
}
Index.cshtml:
<script>
function SubmitForm(form) {
debugger
$.validator.unobtrusive.parse(form);
if ($(form).valid) {
$.ajax({
type: "post",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
</script>
_Layout.cshtml:
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery-ui-1.13.1.min.js"></script>
<script src="~/Scripts/notify.min.js"></script>
EmployeeController.cs:
[HttpPost]
public ActionResult AddOrEdit(Employee emp)
{
using (DBModel db = new DBModel())
{
if (emp.EmployeeID == 0)
{
db.Employees.Add(emp);
db.SaveChanges();
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
else
{
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
return Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet);
}
}
}

After I did update-package in the package manager my submit button has lost is functionality and does nothing

I have a registration form and there is two inputs for password and password confirmation. When I enter distinct values I wanted it to show the error message as 'Passwords should match' or something. So I googled it and found out that update-package should fix this problem. Then I applied this solution in order to fix my problem, now, neither my error message shows up nor my submit button works.
My Registration View:
<div class="container-fluid">
#using (Html.BeginForm("Register", "User", FormMethod.Post, new { #class = "col-12" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal p-3 m-3 w-100 d-flex flex-column align-items-center">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group w-100">
<label class="form-control-label col-md-12">Kullanıcı adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.kullaniciAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.kullaniciAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Firma adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.firmaAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.firmaAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifre, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre tekrar</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifreTekrar, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">E-mail</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.mail, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "text" } })
#Html.ValidationMessageFor(model => model.User.mail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Telefon</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.telefon, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.telefon, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Ülkeniz</label>
#Html.EditorFor(model => model.Address.ulkeID, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value="Türkiye" } })
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz il</label>
<select class="form-control col-md-12" name="Address.sehirID" id="il" required></select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz ilçe</label>
<select class="form-control col-md-12" name="Address.ilceID" id="ilce" disabled required>
<option>Bir İl Seçiniz</option>
</select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Açık adresiniz</label>
<div class="col-md-12">
#Html.EditorFor(model => model.Address.acikAdres, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Oluşturulma Tarihi</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.olusturulmaTarihi, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value=sqlFormat } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<div class="col-md-offset-2 col-md-12">
<input type="submit" value="Kaydol" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
Register Action:
[HttpPost]
public ActionResult Register(RegisterVM model)
{
tblKullanici user = null;
tblAdres address = null;
if(model != null)
{
db = new DatabaseContext();
user = model.User;
address = model.Address;
db.tblKullanici.Add(user);
db.tblAdres.Add(address);
db.SaveChanges();
if (db.SaveChanges() > 0)
{
Session["login"] = model.User;
return RedirectToAction("Index", "App");
}
}
ViewBag.Message = "Kayıt işlemi sırasında hata oluştu!";
return View(model);
}
jQuery
<script>
// ajax call to bring district and city info dynamically according to the city value
$(function () {
$.ajaxSetup({
type: "post",
url: "/User/IlIlce",// target
dataType: "json"
});
$.extend({
ilGetir: function () {
$.ajax({
//sending data
data: { "tip": "ilGetir" },
success: function (sonuc) {
//check result if ok then append it to selectlist
if (sonuc.ok) {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
$("body").append(optionhtml);
});
}
}
});
},
ilceGetir: function (cityID) {
$.ajax({
// then we get the districts with cityID
data: { "ilID": cityID, "tip": "ilceGetir" },
success: function (sonuc) {
// deleting records
$("#ilce option").remove();
if (sonuc.ok) {
// disabled to false
$("#ilce").prop("disabled", false);
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
}
}
});
}
});
// invoke ilGetir to get city values
$.ilGetir();
// on change in city value
$("#il").on("change", function () {
// we get the id of selected value
var cityID = $(this).val();
// and pass it to the ilceGetir function to get the districts
$.ilceGetir(cityID);
});
});
</script>
and the method that ajax call goes:
public JsonResult IlIlce(int? ilID, string tip)
{
db = new DatabaseContext();
List<SelectListItem> sonuc = new List<SelectListItem>();
bool isSuccessful = true;
try
{
switch (tip)
{
case "ilGetir":
// we assign the city values in db to sonuc(result) variable
foreach (var sehir in db.tblSehir.ToList())
{
sonuc.Add(new SelectListItem
{
Text = sehir.sehirAdi,
Value = sehir.sehirID.ToString()
});
}
break;
case "ilceGetir":
// we will fetch districts with sehirID(cityID)
foreach (var ilce in db.tblİlce.Where(il => il.bagliOlduguSehirID == ilID).ToList())
{
sonuc.Add(new SelectListItem
{
Text = ilce.ilceAdi,
Value = ilce.ilceID.ToString()
});
}
break;
default:
break;
}
}
catch (Exception e)
{
// if we encounter an error
isSuccessful = false;
sonuc = new List<SelectListItem>();
sonuc.Add(new SelectListItem
{
Text = e.Message,
Value = "Default"
});
}
// i return the results as json
return Json(new { ok = isSuccessful, text = sonuc });
}
ilce means: district
sehir/il both means: city
sifre: password
kullaniciAdi: username
telefon: phone number
ulke: country
ilGetir : fetch city
ilceGetir: fetch district
kullanici: user
adres: address
sonuc: result
tip: type

Dynamic Add and Edit of Data in Asp.net Mvc using Razor view

I'm new to MVC. Using the scaffolding mechanism I have managed to create CRUD operations on the database table. This works well with working on a single MVC Model at a time (Mapped to a single Model). I want to implement add & edit of a List into database (will be empty list initially), the user should be able to add as many number of items as he need and then submit the data to the database. I want this list to be of dynamic length, so that when user edits the data he should be able to add few more new elements into the Model also deleting few individual Model. I couldn't find proper resource to come up with a solution. Little help will be much Appreciated.
Scenario - Person can have multiple Addresses or Person will not be having any addresses. How to add multiple Address by adding addresses into the view and how to perform edit on those? If one of the Address needs to be deleted then how to do so?
Thank you.
Here is My View:
#model MVC.Models.PersonDetailsViewModel
#{
ViewBag.Title = "AddorEdit";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="container">
<div id="personDetails" class="row">
#Html.HiddenFor(model => model.personModel.PersonId, new { #id = "personId" })
<div class="form-group">
<div class="col-md-2">
<label>First Name</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Last Name</label>
<div style="display:inline;">
#Html.EditorFor(model => model.personModel.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Date of Birth</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.DateOfBirth, new { #id = "dob", htmlAttributes = new { #class = "form-control date-picker" } })
#Html.ValidationMessageFor(model => model.personModel.DateOfBirth, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-1">
<label>Height</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.Height, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.Height, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-1">
<label>Weight</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.Weight, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.Weight, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Location</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.Location, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<br />
<div id="tabs" class="panel panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active">Address</li>
<li>Insuarance</li>
<li>Emergency Contacts</li>
</ul><br />
</div>
<div class="tab-content panel-body">
<div id="tabs-1" class="tab-pane fade in active">
<div style="height:22px">
<a class="btn btn-default" id="btnAdd" style="float:right"><span class="glyphicon glyphicon-plus-sign"></span> Add New Row</a>
</div>
<br />
<div id="mainContent">
<div id="addressDiv">
<div class="col-md-11">
#*#Html.Partial("_Address", Model.addressModel);*#
#{
Html.RenderAction("AddressPartialView", "Person");
}
</div>
<a id="closeAddress" style="margin-top:33px" class="col-md-1 closeLink"><i class="glyphicon glyphicon-trash" style="color:red"></i></a>
</div>
</div>
</div>
<div id="tabs-2" class="tab-pane fade">
#Html.HiddenFor(model => model.insuranceModel.InsuranceId, new { #id = "insuranceId" })
<div class="col-md-4">
<label>Health Plan</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.insuranceModel.HealthPlan, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.insuranceModel.HealthPlan, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<label>Health Plan Type</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.insuranceModel.HealthPlanType, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.insuranceModel.HealthPlanType, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<label>Card Number</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.insuranceModel.CardNumber, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.insuranceModel.CardNumber, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-3" class="tab-pane fade">
#Html.HiddenFor(model => model.emergencyContactModel.EmergencyContactId, new { #id = "emergencyContactId" })
<div class="col-md-3">
<label>Contact Patient</label>
<div style="display:inline">
#{
List<SelectListItem> personItems = new List<SelectListItem>();
personItems.Add(new SelectListItem { Text = "--Select One--", Value = "", Selected = true });
personItems.Add(new SelectListItem { Text = "1", Value = "1" });
personItems.Add(new SelectListItem { Text = "2", Value = "2" });
personItems.Add(new SelectListItem { Text = "3", Value = "3" });
personItems.Add(new SelectListItem { Text = "4", Value = "4" });
}
#Html.DropDownListFor(model => model.emergencyContactModel.ContactPersonId, personItems, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.ContactPersonId, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Relationship Type</label>
<div style="display:inline">
#{
List<SelectListItem> relationshipItems = new List<SelectListItem>();
relationshipItems.Add(new SelectListItem { Text = "--Select One--", Value = "", Selected = true });
relationshipItems.Add(new SelectListItem { Text = "Father", Value = "Father" });
relationshipItems.Add(new SelectListItem { Text = "Mother", Value = "Mother" });
relationshipItems.Add(new SelectListItem { Text = "Son", Value = "Son" });
relationshipItems.Add(new SelectListItem { Text = "Daughter", Value = "Daughter" });
relationshipItems.Add(new SelectListItem { Text = "Guardian", Value = "Guardian" });
}
#Html.DropDownListFor(model => model.emergencyContactModel.RelationshipType, relationshipItems, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.RelationshipType, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Contact Number</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.emergencyContactModel.ContactNumber, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.ContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Email Id</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.emergencyContactModel.EmailId, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.EmailId, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<br />
<div class="col-md-12">
<input type="submit" value="Save" class="btn btn-default" style="margin-top:10px" />
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
And here are my Controller Methods:
public ActionResult AddressPartialView()
{
var _model = new PersonDetailsViewModel();
return PartialView("_Address", _model.addressModel);
}
//To load the data into the form - for editing
public ActionResult AddorEdit(int id = 0)
{
if (id == 0)
{
var myModel = new PersonDetailsViewModel();
return View(myModel);
}
else
{
HttpResponseMessage responsePerson = GlobalVariables.WebApiClient.GetAsync("Person/" + id.ToString()).Result;
HttpResponseMessage responseAddress = GlobalVariables.WebApiClient.GetAsync("Address/" + id.ToString()).Result;
HttpResponseMessage responseInsurance = GlobalVariables.WebApiClient.GetAsync("Insurance/" + id.ToString()).Result;
HttpResponseMessage responseEmergencyContact = GlobalVariables.WebApiClient.GetAsync("EmergencyContact/" + id.ToString()).Result;
var personJsonString = responsePerson.Content.ReadAsStringAsync();
var deserializedPerson = JsonConvert.DeserializeObject<IEnumerable<MvcPersonModel>>(personJsonString.Result);
var addressJsonString = responseAddress.Content.ReadAsStringAsync();
var deserializedAddress = JsonConvert.DeserializeObject<IEnumerable<MvcAddressModel>>(addressJsonString.Result);
var insuranceJsonString = responseInsurance.Content.ReadAsStringAsync();
var deserializedInsurance = JsonConvert.DeserializeObject<IEnumerable<MvcInsuranceModel>>(insuranceJsonString.Result);
var emergencyContactJsonString = responseEmergencyContact.Content.ReadAsStringAsync();
var deserializedEmergencyContact = JsonConvert.DeserializeObject<IEnumerable<MvcEmergencyContactModel>>(emergencyContactJsonString.Result);
var _ViewModel = new PersonDetailsViewModel();
_ViewModel.personModel = deserializedPerson.FirstOrDefault();
_ViewModel.addressModel = deserializedAddress.FirstOrDefault();
_ViewModel.insuranceModel = deserializedInsurance.FirstOrDefault();
_ViewModel.emergencyContactModel = deserializedEmergencyContact.FirstOrDefault();
return View(_ViewModel);
}
}
//Posting data to the database
[HttpPost]
public ActionResult AddorEdit(PersonDetailsViewModel viewModel)
{
HttpResponseMessage responsePerson = GlobalVariables.WebApiClient.PostAsJsonAsync("Person", viewModel.personModel).Result;
HttpResponseMessage responseAddress = GlobalVariables.WebApiClient.PostAsJsonAsync("Address", viewModel.addressModel).Result;
HttpResponseMessage responseInsurance = GlobalVariables.WebApiClient.PostAsJsonAsync("Insurance", viewModel.insuranceModel).Result;
HttpResponseMessage responseEmergencyContact = GlobalVariables.WebApiClient.PostAsJsonAsync("EmergencyContact", viewModel.emergencyContactModel).Result;
return RedirectToAction("Index");
}
I'm using Web API for the backend process. I have added a delete and Add New Row button in the view for Address tab. For now it is working with just a single Model, I wanted to know how to implement it for a Dynamic list, So as to A Person can have 'n' number of Addresses and he can edit whichever he want and also delete based on AddressId. I know the code seems quite low rated. Just want to know the syntax and semantics on how to proceed with working on List. Sorry for Messing up things. Thank you.
Got a solution from Matt lunn.
Follow this link :-
https://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in-asp-mvc-net/
It is implemented by using custom HtmlHelper Extension and creating Html.EditorForMany().
Thanks a lot for the trick Matt Lunn. Works Exactly How I wanted. :)

how to get data from view dropdownlist to controller without using model class in asp.net mvc

Controller
public ActionResult Isearch( string OFFICE_TYPE,string DEPARTMENT, string FILECATEGORY,string fromdate,string todate)
{
ViewBag.officetype = new SelectList(entity.TBL_OFFICETYPE.ToList(), "OFID", "OFFICE_TYPE");
//var list = new SelectList(entity.TBL_OFFICETYPE.Select(r => r.OFFICE_TYPE).ToList());
var list2 = new SelectList(entity.TBL_DEPARTMENT.Select(r => r.DEPARTMENTCODE).ToList());
ViewBag.department = list2;
var list4 = new SelectList(entity.TBL_FILECATEGORY.ToList(), "FILECATEGORY", "FILECATEGORY");
ViewBag.filecategory = list4;
var myinboxdata = entity.TBL_INBOX.ToList();
//var myinboxs = from res in entity.TBL_INBOX
// select new { res.OFFICETYPE, res.DEPARTMENTCODE, res.DESCRIPTION };
var myinbox1=from s in entity.TBL_INBOX select s;
if (String.IsNullOrEmpty(fromdate)&& String.IsNullOrEmpty(todate))
{
//DateTime fdate = Convert.ToDateTime(fromdate).Date;
//DateTime tdate = Convert.ToDateTime(todate).Date;
myinbox1 = entity.TBL_INBOX.Where(s => s.OFFICETYPE.Contains(OFFICE_TYPE) && s.DEPARTMENTCODE.Contains(DEPARTMENT) && s.FILECATEGORY.Contains(FILECATEGORY));
}
else
{
myinbox1 = entity.TBL_INBOX.Where(s => s.OFFICETYPE.Contains(OFFICE_TYPE) && s.DEPARTMENTCODE.Contains(DEPARTMENT) && s.FILECATEGORY.Contains(FILECATEGORY) && (s.UDATE >= Convert.ToDateTime(fromdate).Date && s.UDATE <= Convert.ToDateTime(todate)));
}
var data = myinbox1.OrderBy(x => x.OFFICETYPE).GroupBy(x => new { x.OFFICETYPE, x.DEPARTMENTCODE, x.DESCRIPTION }).Select(g => new { g.Key.OFFICETYPE, g.Key.DEPARTMENTCODE, g.Key.DESCRIPTION, Unread = g.Count() });
List<Inbox> mydata = new List<Models.Inbox>();
foreach (var myinbox in data)
{
mydata.Add(new Models.Inbox { OType = myinbox.OFFICETYPE, DCode = myinbox.DEPARTMENTCODE, Desc = myinbox.DESCRIPTION, Unread = myinbox.Unread });
}
ViewBag.data = mydata.ToList();
return View("Inbox");
}`enter code here`
In thee above code i passing the data from view. While passing the data i am getting the key for office type and department. Instead i want to get their value(text)
View
#using (Html.BeginForm("Isearch", "Transactions", FormMethod.Post))
{
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">My InBox</h3>
</div>
<div class="panel-body">
<div class="col-md-12 col-sm-12">
<div class="form-group col-md-4 col-sm-4">
<label for="Office">OfficeType</label>
#*#Html.DropDownList("officetype", ViewBag.officetype as SelectList, new { #class = "form-control input-sm", #id = "name" })*#
#Html.DropDownList("OFFICE_TYPE", ViewBag.officetype as SelectList, new { #class = "form-control input-sm", #id = "Office",name="Office" })
</div>
<div class="form-group col-md-4 col-sm-4" id="depart">
<label for="DEPARTMENT">Department</label>
#*#Html.DropDownList( ViewBag.Department,Enumerable.Empty<SelectListItem>(), new { #class = "form-control input-sm"})*#,
<select id="DEPARTMENT" name="DEPARTMENT" class = "form-control input-sm" ></select>
</div>
<div class="form-group col-md-4 col-sm-4">
<label for="FILECATEGORY">FILECATEGORY </label>
#Html.DropDownList("FILECATEGORY", ViewBag.filecategory as SelectList, new { #class = "form-control input-sm", #id = "name" })
</div>
<div class="form-group col-md-4 col-sm-4">
<label>From Date</label>
#Html.TextBox("fromdate", null, new { #id = "fromdate", #class = "form-control input-sm" })
#*<input name="fdate" type="text" id="fromdate" class="form-control input-sm" />*#
</div>
<div class="form-group col-md-4 col-sm-4">
<label>To Date</label>
#Html.TextBox("todate", null, new { #id = "todate", #class = "form-control input-sm" })
#*<input type="text" id="todate" class="form-control input-sm" />*#
</div>
<div class="form-group col-md-4 col-sm-4">
<br />
<input type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
the above code is view code where i an passing the value through the id and name property.
In thee above code i passing the data from view. While passing the data i am getting the key for office type and department. Instead i want to get their value(text)
Giving you an example:
<select id="drpgenderid" name="drpgendername">
<option value="1">#Html.Label("FEMALE",Model.gender, new { #style = "", #id = "new_id_gender", #name = "name_new_gender", #placeholder = "Gender", #enabled = "false", #value = "FEMALE" })</option>
<option selected="selected" value="2">#Html.Label("MALE",Model.gender, new { #style = "", #id = "new_id_gender", #name = "name_new_gender", #placeholder = "Gender", #enabled = "false", #value = "MALE" })</option>
</select>
SCRIPT
function GetData()
{
var pdrp = document.getElementById("drpgenderid");
gender = pdrp.options[pdrp.selectedIndex].value;
}
using AJAX
GetData();
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("GetDemoData")",
data: "{'gender':'" + gender.trim() + "'}",
success: function (data) {
}
});
CONTROLLER
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetDemoData(String gender)
{
string gtGender = gender;
}
use ViewBag and #Html.DropDownList we can do drop-down without using model data
In controller
public ActionResult dropdown() {
var customers = new List<Customer>();
customers.Add(new Customer { Name = "Airi Satou", ID = 1 });
customers.Add(new Customer { Name = "Brenden Wagner", ID = 2 });
customers.Add(new Customer { Name = "Brielle Williamson", ID = 2 });
ViewBag.DropData = customers;
return View();
}
In View
#Html.DropDownList("CustomerDropDown", new SelectList(ViewBag.DropData, "ID", "Name"), new { #class="form-control"})
#Html.DropDownList("CustomerDropDown2", new SelectList(ViewBag.DropData, "Name", "Name"), new { #class="form-control"})

getJSON data function doesnt work on IIS

I have a pair of cascading drop down lists for Type & Sub Type. These work perfectly when testing in debug mode locally but once I publish to IIS the sub type list doesnt populate and is blank. I dont get any error messages.
I have tried this in IE9 & also Google Chrome V46 but get the same result.
The controllers are:
public ViewResult StartRA()
{
var user = User.Identity.Name;
string userName = user.Substring(7);
var creator = Peopledb.People.FirstOrDefault(x => x.Username == userName);
var creatorContractId = (int)Session["LoggedContractId"];
StartRiskAssessmentViewModel viewModel = new StartRiskAssessmentViewModel
{
RiskAssessment = new RiskAssessment(),
CreatorId = creator.PersonId,
CreatorContractId = creatorContractId,
Assessor = creator.FirstName + " " + creator.LastName,
Locations = Peopledb.Locations.Where(x => x.Dormant == false).OrderBy(x => x.LocationName).ToList(),
Types = db.Types.Where(x => x.Dormant == false).ToList(),
};
return View(viewModel);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult SubTypeList(int typeId)
{
var subTypes = db.SubTypes.Where(x => x.Dormant == false && x.TypeId == typeId).ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
subTypes,
"SubTypeId",
"SubTypeName"), JsonRequestBehavior.AllowGet
);
return View(subTypes);
}
And the Razor view is:
#model RACentral.ViewModels.StartRiskAssessmentViewModel
#{
ViewBag.Title = "Start RA";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<h3 class="col-md-offset-2">Type</h3>
<div class="form-group">
#Html.LabelFor(model => model.TypeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TypeId, new SelectList(Model.Types, "TypeId", "TypeName", 0), "Please Select", new { #class = "form-control", #id = "Types" })
#Html.ValidationMessageFor(model => model.TypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select id="SubTypes" name="SubTypeId" class="form-control"></select>
#Html.ValidationMessageFor(model => model.SubTypeId, "", new { #class = "text-danger" })
</div>
</div>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" /> #Html.ActionLink("Cancel", "IndexLoggedIn", "Home", null, new { #Class = "btn btn-danger" })
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$("#Types").change(function () {
$.getJSON('#Url.Action("SubTypeList","RiskAssessment")' {
var items = "<option>Please Select</option>";
$.each(data, function (i, subtype) {
items += "<option value='" + subtype.Value + "'>" + subtype.Text + "</option>";
});
$("#SubTypes").html(items);
});
});
</script>
}
You can do this using $.ajax and it might be easier for you to see what's happening
$(function () {
$("#Types").change(function () {
$.ajax({
type: "get", // can change to post easily
data: {typeId: $(this).val()}, // or this.value
url: "#Url.Action("SubTypeList", "RiskAssessment")" // use url helper here
}).done(function (data) {
var items = "<option>Please Select</option>";
$.each(data, function (i, subtype) {
items += "<option value='" + subtype.Value + "'>" + subtype.Text + "</option>";
});
$("#SubTypes").html(items);
});
});
});
using the url helper in your code was the right direction, you just needed to include your params also.
$.getJSON(
"#Url.Action("SubTypeList", "RiskAssessment")",
{ typeId: $(this).val() })
.done(function (data) {
var items = "<option>Please Select</option>";
$.each(data, function (i, subtype) {
items += "<option value='" + subtype.Value + "'>" + subtype.Text + "</option>";
});
$("#SubTypes").html(items);
});

Categories

Resources