how to list dropdown from VIewBag with one to many relation on a partial page? - drop-down-menu

this is my model.
This is a partial page:
#model FinalForm.Models.Employee
<div class="container">
#using (Html.BeginForm("SaveMarks", "Reg", FormMethod.Post))
{
<div class="form-group">
<button type="button" id="Submit" class="btn btn-info col-md-2" onclick="SubmitM()">Add Marks</button>
<div>
<label class="form-label col-md-1">Qualification</label>
#Html.DropDownList("Quallist", null, "Select", htmlAttributes: new { #class = "form-control search-select offerItem Item border border-dark", id = "Item", #Name = "QualificationList.Q_Name" })
#Html.ValidationMessageFor(model => model.EMP_QUALIFICATION, "", new { #class = "text-danger" })
</div>
<div>
<label class="form-label col-md-1">Marks</label>
<input type="text" id="Marks" name="Marks" class="form-control col-md-1" placeholder="" />
</div>
</div>
}
<div class="panel-body">
<table id="tbl_qlist" class="table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Q_id</th>
<th>Q_Name</th>
<th>Marks</th>
<th>Del</th>
</tr>
</thead>
</table>
</div>
</div>
this is contoller method:
[ChildActionOnly]
public ActionResult Equalify()
{
ViewBag.Quallist = new SelectList(new List<QualificationList>(), "Q_id", "Q_Name");
return PartialView("Equalify");
}
```
System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Quallist'.'

Related

Adding new item to database using ASP.NET Core MVC

I'm building a Pet Shop website using ASP.NET Core MVC (the latest version).
I have database with instructions for primary key and identity(1,1) (auto increment).
In my website,in order to check and see if my 'Create' method is working, I've created a page (a controller and view) of Create new animal and a page for the list of all the animals that I've got (Index controller). After clicking Submit on the create page, it's redirected to Index - where I should see the animal that I've added (this line wrote on SQL):
The problem is that I don't see anything added to my list (the photo above). After a few tries, I've tried to add animal directly in my SQL and I saw that it's got the number ID 22 - meaning that maybe I did succeeded to add new animal and I just don't see it?
I really don't know where my problem is and I would be happy to get help.
Controller:
public async Task<IActionResult> Index()
{
var petShopDataContext = _context.Animals.Include(a => a.Category);
return View(await petShopDataContext.ToListAsync());
}
public async Task<IActionResult> CreateAnimal()
{
var categories = await _categoryService.GetAnimalCategory();
ViewBag.Categories = categories.Select(c => new SelectListItem(c.Name, c.CategoryId.ToString())).ToList();
return View();
}
public async Task<IActionResult> CreateAnimal([FromForm] CreateAnimalViewModel vm)
{
vm.Animal.Category = await _categoryService.GetAsync(vm.Animal.CategoryId);
_animalService.AddAnimalAsync(vm.Animal, vm.Photo);
return RedirectToAction("Index");
}
CreateAnimalViewModel:
public class CreateAnimalViewModel
{
public Animal Animal { get; set; }
public IFormFile Photo { get; set; }
}
Create Animal View:
#model PetShop.Client.Models.CreateAnimalViewModel
#{
ViewBag.Title = "CreateAnimal";
}
<h4>Create New Animal</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateAnimal" enctype="multipart/form-data" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Animal.Name" class="control-label"></label>
<input asp-for="Animal.Name" class="form-control" />
<span asp-validation-for="Animal.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Animal.BirthDate" class="control-label"></label>
<input asp-for="Animal.BirthDate" class="form-control" />
<span asp-validation-for="Animal.BirthDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Animal.Description" class="control-label"></label>
<input asp-for="Animal.Description" class="form-control" />
<span asp-validation-for="Animal.Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Animal.Category">Category</label>
<select asp-for="Animal.CategoryId" asp-items="ViewBag.Categories" class ="form-control" id="category"></select>
<span asp-validation-for="Animal.CategoryId" />
<a asp-controller="Admin" asp-action="CreateCategory">
<input type="button" value="Add new category"/>
</a>
</div>
<div class="form-group">
<label asp-for="Photo" class="control-label"></label>
<input type="file" asp-for="Photo" accept="image/*" class="form-control-file"/>
<span asp-validation-for="Photo" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Index View:
#model IEnumerable<PetShop.Data.Models.Animal>
#{
ViewBag.Title = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="CreateAnimal">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.BirthDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.PhotoUrl)
</th>
<th>
#Html.DisplayNameFor(model => model.Category)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.BirthDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhotoUrl)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.AnimalId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.AnimalId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.AnimalId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Animal Service:
public async Task<Animal> AddAnimalAsync(Animal animal, IFormFile image)
{
var entity = _animalRepository.Add(animal);
var path = await _imageService.UploadImage(image, animal);
if (path != String.Empty)
{
return _animalRepository.Update(entity);
}
return entity;
}
Animal Repository:
public Animal Add(Animal entity)
{
_context.Animals.Add(entity);
_context.SaveChanges();
return entity;
}

Repopulate Textbox in PartialView When Page Fails Validation

I have a View that besides being bound to a model, has 3 partial views (a people picker) of a reuseable component. I perform a validation to check for duplicates of the data in the model at submit. If the record is a dup, it redirects back to the page, where the model can repopulate the model fields. However, I'd like the People Picker values to be retained as well, but since it is not part of the model, I don't know how to do that.
This is the controller
public ActionResult Create(IFormCollection collection)
{
try
{
Dept_COEModel Dept = new DeptModel();
Dept.DeptName = collection["DeptName"];
Dept.DeptAcronym = collection["DeptAcronym"];
Dept.DeptCeNtId = collection["UserIdHidden_20"];
Dept.DeptCeUserName = collection["UserNameHidden_20"];
Dept.DeptCeEmail = collection["UserEmailHidden_20"];
Dept.delegate1PocNtId = collection["UserIdHidden_30"];
Dept.delegate1PocName = collection["UserNameHidden_30"];
Dept.delegate1PocEmail = collection["UserEmailHidden_30"];
Dept.delegate2PocNtId = collection["UserIdHidden_40"];
Dept.delegate2PocName = collection["UserNameHidden_40"];
Dept.delegate2PocEmail = collection["UserEmailHidden_40"];
int result = _adoSqlService.CheckDept(collection["DeptName"]);
if (result == 0)
{
_adoSqlService.InsertDept(dept);
return RedirectToAction(nameof(Index));
}
else
{
ModelState.AddModelError("DeptName", "This Department already exists");
ViewData["UserResultTextbox_20"] = Dept.DeptCeUserName;
return View(Dept);
}
}
catch
{
return View(Dept);
}
}
Here is the View
#model EDAD.Models.LOB_COEModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>LOB_COE</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#*<div class="form-group">
<label asp-for="lobCoeId" class="control-label"></label>
<input asp-for="lobCoeId" class="form-control" />
<span asp-validation-for="lobCoeId" class="text-danger"></span>
</div>*#
<div class="form-group">
<label asp-for="lobCoeName" class="control-label"></label>
<input asp-for="lobCoeName" class="form-control" />
<span asp-validation-for="lobCoeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="lobCoeAcronym" class="control-label"></label>
<input asp-for="lobCoeAcronym" class="form-control" />
<span asp-validation-for="lobCoeAcronym" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Select Chief Engineer</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 20 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<label class="control-label">Select Delegate 1</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 30 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<label class="control-label">Select Delegate 2</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 40 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Here is the cshmtl for the People Picker (note that this is reusable so I don't want to modify any code in this)
#model ABC.Models.PeoplePickerViewModel
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/js/site.js"></script>
<script>
$(function () {
setUpGlyphicons(#Model.PickerId, '#Url.Action("SearchForUsers", "PeoplePicker")');
});
</script>
<div class="people-picker">
#Html.TextBox("UserResultTextbox_" + Model.PickerId, Model.User.userName, new { #onkeypress = "userSearchKeyPress(event);", #class = "form-control input-smaller", style = "display: inline", placeholder = "Last Name, First Name", autocomplete = "off" })
#Html.Hidden("UserIdHidden_" + Model.PickerId, Model.User.NTId)
#Html.Hidden("StoredUserNameHidden_" + Model.PickerId, Model.User.userName)
#Html.Hidden("UserNameHidden_" + Model.PickerId, Model.User.userName)
#Html.Hidden("UserEmailHidden_" + Model.PickerId, Model.User.userEmail)
<span id="UserEditButton_#Model.PickerId" class="fa fa-pencil icon-inline"></span>
<span id="UserCancelButton_#Model.PickerId" class="fas fa-ban hide icon-inline"></span>
<span id="UserSearchButton_#Model.PickerId" class="fa fa-search hide icon-inline"></span>
#*<span id="InjectButtonPlaceholder_#Model.PickerId" class="hide"></span>*#
<img id="PeoplePickerLoading_#Model.PickerId" class="hide" alt="Loading..." src="~/Images/loading.gif" /><br />
<span id="PeoplePickerError_#Model.PickerId" class="error-label">*</span>
<div id="UserSearchContent_#Model.PickerId" class="list-group user-results"
onmouseout="$('.disable-scroll-container').removeClass('disable-scroll');"
onmouseover="$('.disable-scroll-container').addClass('disable-scroll');">
</div>
</div>
How can I update the fields that start with the word "User" when the view fails validation
I'm going to close this question. I discovered that the issue lies in a different direction and I'm going to post a new question.

How to send a list of data from controller to a modal popup in razor

I'm implementing asp.net core 3.1 project. I have a razor view and in razor, I'm showing some data that are getting from the Index method in my controller which its name is RequestorsController. In razor, for each row there is a link which is called "Details" and I want when the user clicks on the Details button for each row, the related id for that row passes to a method called "Details" in RequestorsController and a list of related data returns back to the razor view and displays on a Modal popup. Now I could implement the Modal popup, but my problem is I couldn't fetch the data from the controller to show on modal. I appreciate if anyone solves my problem.
<div id="tablecontainer" class="my-5 col-sm-12 d-flex justify-content-center">
<table id="myDummyTable" class="table m-table mytable table-striped mb-4 col-12 dataTable table-bordered px-0 mx-0" style="box-sizing:content-box;">
<thead>
<tr id="headerrow">
<th>
requestor name
</th>
<th>
items requested
</th>
<th>
operations
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.HiddenFor(modelItem => item.applicantID)
#Html.DisplayFor(modelItem => item.requestorName)
</td>
<td>
#Html.DisplayFor(modelItem => item.requesteditemCount)
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-id="#item.applicantID">Details</button>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="post">
<div class="modal-body">
<div class="form-group">
<label for="recipient-apiname" class="col-form-label">name:</label>
<input type="text" class="form-control" id="recipient-apiname" name="apiname">
<input type="hidden" id="recipient-id" name="id" />
</div>
<div class="form-group">
<label for="recipient-status" class="col-form-label">status:</label>
<input type="text" class="form-control" id="recipient-status" name="status">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
#section scripts{
<script>
#{
if (ViewBag.ModalState == null)
{
ViewBag.ModalState = "hide";
}
}
$('#exampleModal').modal('#ViewBag.ModalState');
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var id = button.data('id');
var modal = $(this);
modal.find('.modal-body input[name="id"]').val(id);
$.get('#Url.Action("Details", "Requestors")/' + id, function (data) {
modal.find('.modal-body input[name="name"]').val(data.itemName);
modal.find('.modal-body input[name="status"]').val(data.requestStatus);
});
});
</script>
}
public async Task<IActionResult> Details(int? id)
{
List<ItemDTO> al = new List<ItemDTO>();
ItemDTO apDTO;
var myquery = (from t in _context.Items
where t.ApplicantId == id
select new { ItemName = t.ItemName, requestStatus = t.LastRequestStatus }).ToList();
foreach (var index in myquery)
{
apDTO = new ItemDTO();
apDTO.itemName = index.itemName;
apDTO.requestStatus = index.requestStatus;
al.Add(apDTO);
}
return View(al);
}
Now I could implement the Modal popup, but my problem is I couldn't
fetch the data from the controller to show on modal.
As mentioned in your comment, when you click on the Details button, a 500 error occurs,I did reproduce this mistake.
This is because the Details action returns the View instead of the json data that needs to be returned in ajax, and because there is no Details view, a 500 error occurs.
To solve it, you only need to change the content of the Details action returned to Json data, as shown below:
public async Task<IActionResult> Details(int? id)
{
List<ItemDTO> al = new List<ItemDTO>();
ItemDTO apDTO;
var myquery = (from t in _context.Items
where t.ApplicantId == id
select new { ItemName = t.ItemName, requestStatus = t.LastRequestStatus }).ToList();
foreach (var index in myquery)
{
apDTO = new ItemDTO();
apDTO.itemName = index.ItemName;// here is ItemName(case sensitive)
apDTO.requestStatus = index.requestStatus;
al.Add(apDTO);
}
return Json(al);
}
My doubt is that if the ApplicantId is the key, then the count of data obtained from the Items table must be one, without the need for a list collection, but because you return a collection data, then in ajax, you need to pass data[0] to bind the corresponding input value/
And you need to change input[name="name"] to input[name="apiname"].
Here is ajax code:
$.get('#Url.Action("Details", "Requestors")/' + id, function (data) {
modal.find('.modal-body input[name="apiname"]').val(data[0].itemName);
modal.find('.modal-body input[name="status"]').val(data[0].requestStatus);
});

Ajax.BeginForm submitting the form twice

I have a problem with my modal on inserting data. Every time I add a new row it get's a second identical row into the database. I don't really know exactly what I did wrong so if you have a ideea on how to solve this please help me.
This is my controller:
public ActionResult IndexEvent()
{
return View(db.tbl_Event.ToList());
}
[HttpGet]
public ActionResult AddEvent()
{
return PartialView();
}
[HttpPost]
public ActionResult AddEvent(BOL3.tbl_Event eve)
{
if(ModelState.IsValid)
{
db.tbl_Event.Add(eve);
db.SaveChanges();
}
return PartialView("_Detail", db.tbl_Event.ToList());
}
,here is my Index view, _Detail partial view and Add partial view (in the same order):
#model IEnumerable<BOL3.tbl_Event>
#{
ViewBag.Title = "Index";
}
<link href="#Url.Content("~/Content/bootstrap/css/bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/bootstrap/css/bootstrap-theme.min.cs")" rel="stylesheet" />
<link href="#Url.Content("~/Content/bootstrap/css/font-awesome.min.cs")" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<div id="main-div">
<div class="clearfix"> </div>
<div class="clearfix"> </div>
<div class="container">
<i class="glyphicon glyphicon-plus"></i> Add New
<br />
<br />
<div id="div-record">
#Html.Partial("_Detail")
</div>
</div>
</div>
<div class="modal fade" id="Add-Model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Event</h4>
</div>
<div class="divForAdd">
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#Add').click(function (event) {
event.preventDefault();
$.get(this.href, function (response) {
$('.divForAdd').html(response);
});
$('#Add-Model').modal({
backdrop: 'static',
}, 'show');
});
#model IEnumerable<BOL3.tbl_Event>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Event Name</th>
<th>Starting Event (Date and Time)</th>
<th>Ending Event (Date and time)</th>
<th>All Day ?</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Event)
</td>
<td>
#Html.DisplayFor(modelItem => item.Start_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.End_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.All_Day)
</td>
<td>
<i class="glyphicon glyphicon-pencil"></i> Edit
</td>
<td>
#Ajax.ActionLink(" Delete", "DeleteEvent", "Prog", new { #id = item.ID }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div-record" }, new { #class = "glyphicon glyphicon-trash" })
</td>
</tr>
}
</tbody>
</table>
</div>
#model BOL3.tbl_Event
#using (Ajax.BeginForm("AddEvent", "Prog", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "div-record", OnSuccess = "$('.close').click()" }))
{
<div class="modal-body">
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pushpin"></i></span>
#Html.TextBoxFor(m => m.Event, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.Start_Date, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.End_Date, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.All_Day, new { #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" name="cmd">Save</button>
</div>
}
I tried something else but that also gave me a problem (see this link: "Refresh table list using Ajax in Asp.Net Mvc") Thank you.
this problem is occuring because you have loaded <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> twice in the _layout page as well as index page and because of that it causes ajax to send request twice. so remove the link either from Index page or _layout page
Why it causes to submit twice?
if you look at the code of unobtrusive-ajax it has function $(document).on("click", "form[data-ajax=true] which is responsible for sending the request so when you submit the form this function trigger's differently on each script you loaded which causes the request to send twice (if someone can explain better feel free to edit)
It is because you have JS function binded to element #Add and you are not disabling anchror href correctly, thus having two requests (since your anchor has link attribute as well). In this SO question How can I disable HREF if onclick is executed? you can se, that correct click handling should be like
$('#Add').click(function (event) {
event.preventDefault();
$.get(this.href, function (response) {
$('.divForAdd').html(response);
});
$('#Add-Model').modal({
backdrop: 'static',
}, 'show');
return false; // this is essential
});

MVC5 Ajax.BeginForm, UpdateTargetId no render PartialView

I have a problem with my MVC application.
My controller:
public class CustomerController : Controller
{
CustomerFacade cf = new CustomerFacade();
public ActionResult Create()
{
return View();
}
[HttpPost]
public void Create(Customers customers)
{
if (customers != null)
{
cf.CreateCustomer(customers, UserSession.UserId);
}
// return View();
}
public ActionResult GetAllCustomers()
{
var allCustomers = cf.GetAllCustomers();
return PartialView("InsuranceCustomer", allCustomers);
}
}
My main view:
<div class="x_content">
<div id="mainb" style="height:350px;">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
<i class="fa fa-plus"></i>
</button>
#*render modal*#
#Html.Partial("~/Views/Customer/CreateModal.cshtml")
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
<i class="fa fa-database"></i>
</button>
#*render modal*#
<div id="customerId">
#Html.Action("GetAllCustomers", "Customer")
</div>
</div>
</div>
The partial view CreateModal.cshtml is a form on bootstrap modalpopup:
for example:
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Customer", null, new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "customerId",
OnSuccess = "$('#customerModal').modal('hide')"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-4">
#Html.TextBoxFor(model => model.FirstName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.FirstName })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(model => model.LastName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.LastName })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
// and other field form
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="#Resources.Common.Save" class="btn btn-success" />
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
</div>
and InsuranceCustomer looks like:
#model IEnumerable<Insurance_System.Models.Customers>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
</tr>}
I want to after submiting modal CreateModal loaded again InsuranceCustomer with new element without reloading page.
(sorry for my bad English)
in the controller
public ActionResult Create()
{
return View();
}
[HttpPost]
public void Create(Customers customers)
{
var cust = new customer
{
name=customers.name,
etc....
}
db.customers.add(cust);
db.savechanges();
var listcustomers = db.customers.ToList();
return PartialView("InsuranceCustomer",listcustomers);
}
in the View
<div class="x_content">
<div id="mainb" style="height:350px;">
<div id="customerId">
#*here will be load your partialview*#
</div>
</div>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Customer", null, new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "customerId",
OnSuccess = "$('#customerModal').modal('hide')"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-4">
#Html.TextBoxFor(model => model.FirstName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.FirstName })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(model => model.LastName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.LastName })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
// and other field form
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="#Resources.Common.Save" class="btn btn-success" />
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
</div>
in the partial view
#model IEnumerable<Insurance_System.Models.Customers>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
</tr>}

Resources