MVC 5 Edit Bootstrap Modal Popup - c#

I have the following View
#model QuotationManagement.Models.ProductViewModel
#{
ViewBag.Title = "Products";
}
<h2>Products</h2>
<button id='newProduct' data-toggle="modal" data-target="#newProductModal" class="btn btn-primary">Add New Product</button>
<br />
#using (Html.BeginForm("Products", "Main", FormMethod.Post, new { encType = "multipart/form-data", name = "myform" }))
{
<table class="table table-bordered table-condensed table-striped">
<tr>
<th>
Name
</th>
<th>
Price
</th>
<th>
Gender
</th>
<td>
Action
</td>
</tr>
#Html.EditorFor(model => model.Products)
</table>
}
<div id="newProductModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
#using (Html.BeginForm("NewProduct", "Main", FormMethod.Post, new { encType = "multipart/form-data", name = "newProdutForm", #class = "form-group" }))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">New Product</h4>
</div>
<div class="modal-body">
#Html.HiddenFor(model => model.NewProduct.Id)
Name:
#Html.TextBoxFor(model => model.NewProduct.Name, new { #class = "form-control" })
Price:
#Html.TextBoxFor(model => model.NewProduct.Price, new { #class = "form-control" })
Gender:
#Html.DropDownListFor(model => model.NewProduct.ForGender, new List<SelectListItem>() { new SelectListItem() { Text = "Male", Value = "1" }, new SelectListItem() { Text = "Female", Value = "2" } }, new { #class = "form-control" })
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
}
</div>
</div>
</div>
And then the Template
#model QuotationManagement.Bussiness_Logic_Layer.Product
<tr>
<td>
#Html.HiddenFor(model => model.Id)
#Html.DisplayFor(model => model.Name)
</td>
<td>
#Html.DisplayFor(model => model.Price)
</td>
<td>
#Html.DisplayFor(model => model.Gender)
</td>
<td>
#Html.ActionLink("Edit", "EditProduct","Main", Model ,new { #class = "btn btn-primary"})
</td>
</tr>
Adding a new Product works, but now I want to change the edit Button to Bind the row item to the Boostrap Popup and then opens it for editing.
The current method I am trying is with the ActionLink which then takes the selected Product and binds it to ProductViewModel.NewProduct, which works but now my problem is I will need to reload the whole page and repopulate the table and then somehow open the Boostrap Modal.
So my question is
How can I Bind the Selected Product to the Modal and then show the Modal withoud having to do a postback or without having to reload the current page

I would recommend using AJAX and a single 'Edit' modal which would be cleared and repopulated when the user clicks 'edit' for each row.
Essentially, you will have a partial view which will be called via AJAX and injected onto the page, the method will have a parameter of productId.
Template
Please note the important part here is the onclick attribute of the edit button.
#model QuotationManagement.Bussiness_Logic_Layer.Product
<tr>
<td>
#Html.HiddenFor(model => model.Id)
#Html.DisplayFor(model => model.Name)
</td>
<td>
#Html.DisplayFor(model => model.Price)
</td>
<td>
#Html.DisplayFor(model => model.Gender)
</td>
<td>
Edit
</td>
</tr>
Javascript
$(function() {
$('.editModal').modal();
});
function editProduct(productId) {
$.ajax({
url: '/Product/GetProductDetailsModal/' + productId, // The method name + paramater
success: function(data) {
$('#modalWrapper').html(data); // This should be an empty div where you can inject your new html (the partial view)
}
});
}
Add the following to your top-level view
<div id="modalWrapper">
#* Inject form here *#
</div>
Partial View
Your partial view will look something like this
#model ProductModel
<div class="modal fade" id="editModal">
<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">Edit</h4>
</div>
<div class="modal-body">
<form>
<input type="text" id="ProductName" value="#Model.Name"/>
<input type="submit" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Related

Unable to pass list to controller with data table. ASP.net

I have a cshtml page that will be sending a list of items over to my controller. However when i click on the submit button, nothing is being passed over to my controller.
The codes below is my cshtml codes which will pass the model over to my controller.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
#if (Model.Count() != 0)
{
<input type='button' value='Save and Update' class="btn btn-primary" data-toggle="modal" data-target="#myModal" />
}
</div>
<table class="table cell-border" id="TempTable5">
<tbody>
#if (Model.Count() != 0)
{
int j = 0;
foreach (var item in Model)
{
#Html.HiddenFor(model => item.ExerciseInstruction.ExerciseInstructionID)
<tr>
<td align="center">
<div class="form-group">
#Html.DisplayFor(model => item.ExerciseInstruction.ExerciseInstructionID)
</div>
</td>
<td>
<div class="form-group">
#Html.DisplayFor(model => item.Exercise.Name)
</div>
</td>
<td>
<div class="form-group">
<iframe width="300" height="175" src=#item.ExerciseVideo.VideoURL frameborder="0" allowfullscreen></iframe>
</div>
</td>
<td align="center">
#Html.DisplayFor(model => item.Therapist.Name)
</td>
<td>
#Html.DisplayFor(model => item.ExerciseInstruction.Prescribed_Date)
</td>
<td>
No. of Reps: #item.ExerciseInstruction.Number_Of_Reps<br />
No. of Secs to hold: #item.ExerciseInstruction.Number_Of_Secs_PositionHold<br />
No. of Sets: #item.ExerciseInstruction.Number_Of_Sets_Per_Day<br />
No. of Times: #item.ExerciseInstruction.Frequency_Per_Week<br />
Remarks: #if (item.ExerciseInstruction.Remark == null || item.ExerciseInstruction.Remark.Trim() == "")
{
#:NIL
}
else
{
#item.ExerciseInstruction.Remark
}
</td>
<td align="center">
#Html.EditorFor(model => item.ExerciseInstruction.ToPerform, new { htmlAttributes = new { style = "width:23px; height:23px;" } })
</td>
<td>
#Html.ActionLink("View", "Details", new { id = Model[j].ExerciseInstruction.ExerciseInstructionID, pageFrom = "performExercises" }, new { target = "_blank" })
</td>
</tr>
j++;
}
}
</tbody>
</table>
#if (Model.Count() != 0)
{
<input type='submit' value='Save and Update' class="btn btn-primary" data-toggle="modal" data-target="#myModal" />
}
}
The controller that is working on this is as below.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Therapist")]
public ActionResult ToPerformExercises(int? pid, List<AssignmentViewModel> avmLIst)
{
if (ModelState.IsValid)
{
foreach (var item in avmLIst)
{
ExerciseInstruction eI = db.ExerciseInstructions.SingleOrDefault(a => a.ExerciseInstructionID == item.ExerciseInstruction.ExerciseInstructionID);
eI.ToPerform = item.ExerciseInstruction.ToPerform;
db.Entry(eI).State = EntityState.Modified;
db.SaveChanges();
}
}
return RedirectToAction("ViewToPerform", "AssignExercisesViewModel", new { pid = pid });
}
This is the submit pop up box
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!— Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to add/remove the Ongoing Exercise(s) for the patient?</p>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-primary" value="Confirm" onclick="DisableButton(this)" />
<button type="button" class="btn btn-default" data-dismiss="modal" id="cancel">Cancel</button>
</div>
</div>
</div>
</div>
My problem is very similar to this link Jquery tool DataTable unable to post/submit in an MVC3 Html.BeginForm
However i am unsure of how he actually solve it as the explanation on his answer was really brief.
Can anyone assist?
There's a lot going on here, but I'll take a shot at it based on a common pitfall in model binding... You should change the foreach to a for loop, then alter your HtmlEditorFor calls to use the index.
So to greatly simplify what you have above...
for(int i = 0; i < model.Count; i++)
{
// other things
#Html.EditorFor(model => model[i]. //rest of stuff
// more other things
MVC serializes a name into the element for you, then attempts to re-map this server-side when posting the form. If you use a foreach loop in this way, it will lose the index and fail to bind.
You can see this effect happening if you watch your requests in Fiddler (or Chrome or whatever).
Check out this answer. They experienced a similar problem when using foreach instead of for. The model binding does not work in the former case.
Model.List is null on POST using Razor

Partial view button submit not call httpost, call a action to view

view :
<div id="ReportChange">
#{
ViewDataDictionary vDataDictonary = new ViewDataDictionary();
vDataDictonary.Add(new KeyValuePair<string, object>("ReportType", ViewData["ReportType"]));
vDataDictonary.Add(new KeyValuePair<string,object>("Agencias", ViewData["Agencias"]));
vDataDictonary.Add(new KeyValuePair<string, object>("SendType", ViewData["SendType"]));
vDataDictonary.Add(new KeyValuePair<string, object>("OrderStatus", ViewData["OrderStatus"]));
vDataDictonary.Add(new KeyValuePair<string, object>("User", ViewData["User"]));
vDataDictonary.Add(new KeyValuePair<string, object>("ServicesType", ViewData["ServicesType"]));
if (Model.report == null){
Html.RenderPartial("getReport", new ReportSchedule() { StartDate = DateTime.Now, EndDate=DateTime.Now}, vDataDictonary);
}
else {
Html.RenderPartial("getReport", Model.report, vDataDictonary);
}
}
#if (Model.lReport.Count() == 0)
{
<h4 class="alert alert-danger text-center">Error.</h4>
}
else
{
<div class="container-fluid container-fixed-lg bg-white" id="viewform">
<div class="panel panel-transparent">
<div class="panel-heading">
<div class="panel-title"></div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<table class="table table-hover demo-table-search" id="tableWithSearch">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.lReport)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.ReportType.Description)</td>
<td>#(item.EndDate.HasValue ? String.Concat(item.StartDate.ToString("dd/MM/yyyy"), " - ", item.EndDate.Value.ToString("dd/MM/yyyy")) : item.StartDate.ToString("dd/MM/yyyy"))</td>
<td>#item.StartDate - #item.EndTime </td>
<td>#Html.DisplayFor(modelItem=> item.Agency.CorporateName) </td>
<td>#Html.DisplayFor(modelItem=> item.CostCenter.Description)</td>
<td>#Html.DisplayFor(modelItem=> item.User.Name )</td>
<td>#Html.DisplayFor(modelItem=>item.OrderStatus.Description ) </td>
<td>#Html.DisplayFor(modelItem=> item.ServiceType.Description ) </td>
<td>#Html.CheckBox("A", #item.Live.Equals(0) ? false : true, new {disabled="readonly" })</td>
<td class="v-align-middle">
<div class="btn-group">
<input type="button" class="btn btn-info btn-sm" id="#item.ReportScheduleID" onclick="getReport(this.id)" />
#Html.ActionLink(item.Live ? "D" : "A", "Live", new { id = item.CostCenterID }, new { #class ="btn btn-danger btn-sm buttonLive" })
</div>
</td>
</tr>
}
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
</div>
}
My partial view :
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<form id="frm" class="form-horizontal well">
#if (Model.AgencyID.Equals(0))
{
using (Html.BeginForm("getReport", "ReportSchedules"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(_ => _.ReportScheduleID)
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-1">Relatório</label>
#Html.DropDownListFor(m=>m.ReportTypeID,(SelectList) ViewData["ReportType"],"Atendimento por Agência")
#Html.ValidationMessageFor(m=>m.ReportTypeID)
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-1">Início</label>
<input type="text" id="date" name="date" class="col-md-2 smallDate" value="#Model.StartDate.ToShortDateString()"/>
#Html.ValidationMessageFor(m=>m.StartDate)
#Html.TextBoxFor(m=>m.StartTime,new {#class="col-md-1 smallDateMargin"})
#Html.ValidationMessageFor(m => m.StartTime)
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-1">Periodicidade</label>
#Html.DropDownListFor(m=>m.SendTypeID,(SelectList) ViewData["SendType"],"Selecione")
#Html.ValidationMessageFor(m=>m.SendTypeID)
</div>
</div>
<div class="col-md-10">
<h6>Configurações avançadas<a data-toggle="tooltip" class="tooltipLink" data-original-title="Data até quando o relatório será enviado.">
<span class="glyphicon glyphicon-question-sign"></span>
</a></h6>
<div class="form-group" style="border: 1px dashed #ccc;">
<div class="form-group">
<label class="control-label col-md-1">
<input type="checkbox" name="dateEndSelected" id="dateEndSelected" value="#Model.Live"/> Fim</label>
<input type="text" id="dataFinalSelected" name="dataFinalSelected" style="display:none;" value="false"/>
<input type="text" id="dateFinal" name="dateFinal" style="display:none;"class="col-md-2 smallDate" value="#Model.EndDate.Value.ToShortDateString()"/>
#Html.TextBoxFor(m=>m.EndTime,new {#class="col-md-1 smallDateMargin"})
#Html.ValidationMessageFor(m=>m.EndTime)
</div>
</div>
</div>
<div class="col-md-10">
<h6>Filtrar por:</h6>
<div class="form-group" style="border: 1px dashed #ccc;">
<div class="col-md-10">
#Html.DropDownListFor(m=>m.AgencyID, (SelectList) ViewData["Agencias"],"Agências",new {#class="col-md-1",id="agencia",name="agencia"})
#Html.ValidationMessageFor(m => m.AgencyID)
#Html.DropDownListFor(m=>m.OrderStatusID, (SelectList) ViewData["OrderStatus"],"Status",new {#class="col-md-2"})
#Html.ValidationMessageFor(m=>m.OrderStatusID)
#Html.DropDownListFor(m=>m.UserID, (SelectList) ViewData["User"],"Usuários",new {#class="col-md-3"})
#Html.ValidationMessageFor(m=>m.UserID)
</div>
<div class="col-md-10">
#Html.DropDownList("dpdCostCenter", new List<SelectListItem>(), "Selecione", new { #class = "col-md-1" })
#Html.DropDownListFor(m=>m.ServiceTypeID,(SelectList) ViewData["ServicesType"],"Tipos de atendimento",new {#class="col-md-2"})
#Html.ValidationMessageFor(m=>m.ServiceTypeID)
</div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<div class="input-group pull-right marginTopBot-sm input-group-sm" style="padding-left: 5px;">
<input type="submit" value="Agendar o envio" class="btn btn-success" onclick="$('#getResponse').submit()" />
</div>
</div>
</div>
</div>
}
}
else
But if i click in button submit it goes to the index action of view
public ActionResult Index()
And not to :
[HTTPPOST]
public ActionResult getReport(ReportSchedule model)
{
if (ModelState.IsValid)
{
db.ReportSchedule.Add(model);
db.SaveChanges();
}
else
{
return PartialView(model);
}
return RedirectToAction("Index");
}
But i need submit button call getReport to validate a model and save in db
You have nested forms which are invalid html and not supported. Remove the outer form tag from the partial (including the AntiForgeryToken and ValidationSummary above it
<form id="frm" class="form-horizontal well"> // remove this and its corresponding closing tag

The value of the property '$' is null or undefined, not a Function object

I'm developing purchase module with ASP.NET MVC 5. In Create view purchase, I'm using PartialView to load the detail purchase.
The Detail Purchase contains:
A textbox with browse button to input item
A textbox to input quantity
A button to add the item to the list (purchase detail)
When I clicked browse button the modal will show up with list of paged items (using PagedList). The modal form contains:
In modal header there are a textbox and a button for searching item name
In modal body to display list of items (load partially)
The error occurs if I searched item name
"The value of the property '$' is null or undefined, not a Function
object"
The jQuery script is already added by default at ~/Shared/_Layout.cshtml, and in the create view, I have added #Scripts.Render("~/bundles/jqueryval")
Code: View Create Purchase (Create.cshtml)
#model SalesSupportSystem.ViewModels.PurchaseOrderViewModel
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>PurchaseOrder</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.PurchaseOrderDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PurchaseOrderDate)
#Html.ValidationMessageFor(model => model.PurchaseOrderDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.InvoiceNo, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.InvoiceNo)
#Html.ValidationMessageFor(model => model.InvoiceNo)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#{ Html.RenderPartial("~/Views/PurchaseOrderDetail/_AddEdit.cshtml", Model.PurchaseOrderAddEditDetails); }
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<script>
$(document).ready(function () {
$(".date").datepicker({
autoclose: true,
clearBtn: true,
format: "dd/mm/yyyy",
todayBtn: "linked",
todayHighlight: true
});
$("#btnLookupItem").click(function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "#Url.Content("~/INVENTSUM1/Lookup")",
cache: false
})
.done(function (data) {
$("#itemContainer").html(data);
$("#itemModal").modal("show");
});
});
$("#btnSubmitINVENTSUM1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "#Url.Content("~/INVENTSUM1/Lookup")",
data: { filterValue: $("#FilterValue").val() },
cache: false
})
.done(function (data) {
$("#itemContainer").html(data);
});
});
});
function setINVENTSUM1(ITEMID, ITEMNAME) {
document.getElementById("ItemID").value = ITEMID;
document.getElementById("ItemName").value = ITEMNAME;
$("#itemModal").modal("hide");
}
</script>
}
PartialView (_AddEdit.cshtml)
#model SalesSupportSystem.ViewModels.PurchaseOrderDetailAddEditViewModel
<!-- Item Modal -->
<div class="modal fade bs-example-modal-lg" id="itemModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" id="btnCancelCUSTTABLE" title="Clear the selected input on form" class="close" data-dismiss="modal" data-toggle="tooltip" data-placement="left"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Select Item</h4>
#using (Html.BeginForm("Lookup", "INVENTSUM1"))
{
<div class="form-inline">
Find by name: <input type="text" id="FilterValue" name="FilterValue" class="form-control" placeholder="Enter keyword" value="" />
<input type="submit" id="btnSubmitCUSTTABLE" value="Search" class="btn btn-primary" />
</div>
}
</div>
<div class="modal-body" id="itemContainer">
...
</div>
</div>
</div>
</div>
#using (Html.BeginForm("AddEdit", "PurchaseOrderDetail", FormMethod.Get, new { #class = "form-inline" }))
{
<h4>Detail</h4>
<hr />
<fieldset>
<div class="form-inline">
<div class="form-group">
#Html.HiddenFor(model => model.ItemID)
<div class="input-group">
#Html.EditorFor(model => model.ItemName)
<div class="input-group-btn">
<button class="btn btn-primary" id="btnLookupItem">...</button>
</div>
</div>
</div>
<div class="form-group">
#Html.EditorFor(model => model.QuantityOrder)
</div>
<button class="btn btn-primary" id="btnAddItem">Add</button>
</div>
</fieldset>
}
Controller (INVENTSUM1Controller.cs)
public ActionResult Lookup(int? page)
{
var pagedItem = db.INVENTSUM1
.OrderBy(i => i.ITEMNAME)
.ToPagedList(page, 10);
return PartialView("_Lookup", pagedItem);
}
[HttpPost]
public ActionResult Lookup(string filterValue)
{
var pagedItem = db.INVENTSUM1
.Where(i => i.ITEMNAME.Contains(filterValue))
.OrderBy(i => i.ITEMNAME)
.ToPagedList(1, 10);
return PartialView("_Lookup", pagedItem);
}
PartialView (_Lookup.cshtml)
#model IEnumerable<SalesSupportSystem.Models.INVENTSUM1>
#using PagedList.Mvc;
#{
var pagedList = (PagedList.IPagedList)Model;
}
<div>
<table class="table table-striped table-hover table-condensed">
<tr>
<th></th>
<th>
#Html.DisplayNameFor(model => model.ITEMID)
</th>
<th>
#Html.DisplayNameFor(model => model.ITEMNAME)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td></td>
<td>#Html.DisplayFor(modelItem => item.ITEMID)</td>
<td>#Html.DisplayFor(modelItem => item.ITEMNAME)</td>
</tr>
}
</table>
</div>
Page #(pagedList.PageCount < pagedList.PageNumber ? 0 : pagedList.PageNumber) of #pagedList.PageCount
<div id="pager">
#Html.PagedListPager(pagedList, page => Url.Action("Lookup", new { page }))
</div>
<script>
$(document).ready(function () {
$("#pager").on("click", "a", function () {
if (this.href == "") {
return;
}
$.ajax({
type: "GET",
url: this.href,
cache: false
})
.done(function (data) {
$("#itemContainer").html(data);
});
return false;
});
});
</script>
Another question: as you can see in the lookup.cshtml code, I placed script at there. I've read from SO articles, it should not be placed in partialview, but I have no choice, if I placed in Create.cshtml, the paging will not work. Is there any workaround for this?

Multiple forms on a single MVC page

Below is a screenshot of my page. It has 3 tabs - Details, Users and Rights. Each tab has its own submit button which I need to fire different code within the controller (of which there is no code as of yet).
My question is, how to I have 3 separate forms on a single MVC page and how do I get each Submit button to run the respective code?
View
<div class="row-fluid">
<div class="span12">
<!-- BEGIN INLINE TABS PORTLET-->
<div class="widget">
<div class="widget-title">
<h4><i class="icon-user"></i></h4>
</div>
<div class="widget-body">
<div class="row-fluid">
<div class="span8">
<!--BEGIN TABS-->
<div class="tabbable custom-tab">
<ul class="nav nav-tabs">
<li class="active">Role Details</li>
<li>Users</li>
<li>Rights</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab_1_1">
#using (Html.BeginForm("Details", "RoleController", FormMethod.Get, new { }))
{
#Html.ValidationSummary(true)
<div class="row-fluid">
<div class="span3">
#Html.HiddenFor(model => model.Id)
<div class="control-group">
<label class="control-label">#Html.DisplayNameFor(model => model.RoleName)</label>
<div class="controls controls-row">
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.DisplayNameFor(model => model.Description)</label>
<div class="controls controls-row">
#Html.TextArea("Description", Model.Description, new { #cols = 400, #rows = 10 })
</div>
</div>
</div>
</div>
<input type="submit" class="btn btn-success" value="Save" />
}
</div>
<div class="tab-pane" id="tab_1_2">
#using (Html.BeginForm("UsersForRole", "RoleController", FormMethod.Post, new { }))
{
<!-- BEGIN DUAL SELECT-->
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTk5MjI0ODUwOWRkJySmk0TGHOhSY+d9BU9NHeCKW6o=" />
</div>
<div>
<table style="width: 100%;" class="">
<tr>
<td style="width: 35%">
<div class="d-sel-filter">
<span>Filter:</span>
<input type="text" id="box1Filter" />
<button type="button" class="btn" id="box1Clear">X</button>
</div>
<select id="box1View" multiple="multiple" style="height: 300px; width: 75%" runat="server">
</select><br />
<span id="box1Counter" class="countLabel"></span>
<select id="box1Storage">
</select>
</td>
<td style="width: 21%; vertical-align: middle">
<button id="to2" class="btn" type="button"> > </button>
<button id="allTo2" class="btn" type="button"> >> </button>
<button id="allTo1" class="btn" type="button"> << </button>
<button id="to1" class="btn" type="button"> < </button>
</td>
<td style="width: 35%">
<div class="d-sel-filter">
<span>Filter:</span>
<input type="text" id="box2Filter" />
<button type="button" class="btn" id="box2Clear">X</button>
</div>
<select id="box2View" multiple="multiple" style="height: 300px; width: 75%;">
#foreach (var user in Model.Users)
{
<option>#Html.DisplayFor(model => user.SurnameFirstName)</option>
}
</select><br />
<span id="box2Counter" class="countLabel"></span>
<select id="box2Storage">
</select>
</td>
</tr>
</table>
</div>
<div class="mtop20">
<input type="submit" value="Submit" class="btn" />
</div>
<!-- END DUAL SELECT-->
}
</div>
<div class="tab-pane" id="tab_1_3">
#using (Html.BeginForm("RightsForRole", "RoleController", FormMethod.Post, new { }))
{
<table class="table table-striped">
<thead>
<tr>
<th>Right Name</th>
<th>Description</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var right in Model.Rights)
{
<tr>
<td>#Html.DisplayFor(model => right.RightName)</td>
<td>#Html.DisplayFor(model => right.Description)</td>
<td>
<div class="success-toggle-button">
#Html.CheckBoxFor(model => right.Assigned, new { #class = "toggle" })
</div>
</td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
</div>
<!--END TABS-->
</div>
<div class="span4">
<div class="control-group">
<label class="control-label">#Html.DisplayNameFor(model => model.DateCreated)</label>
<div class="controls controls-row">
#Html.EditorFor(model => model.DateCreated, new { #readonly = "readonly" })
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.DisplayNameFor(model => model.CreatedBy)</label>
<div class="controls controls-row">
#Html.EditorFor(model => model.CreatedBy, new { #readonly = "readonly" })
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.DisplayNameFor(model => model.LastUpdated)</label>
<div class="controls controls-row">
#Html.EditorFor(model => model.LastUpdated)
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.DisplayNameFor(model => model.LastUpdateBy)</label>
<div class="controls controls-row">
#Html.EditorFor(model => model.LastUpdateBy)
</div>
</div>
</div>
</div>
</div>
</div>
</div>
UsersForRole controller
[HttpPost]
public ActionResult UsersForRole(RoleModel model)
{
if (ModelState.IsValid)
{
}
return View(model);
}
I think that you may have something wrong in this line:
#using (Html.BeginForm("UsersForRole", "RoleController", FormMethod.Post, new { }))
Controler name in the Html.BeginForm shoudl be only Role unless your controller name is`RoleControllerController?
What you are doing looks fine, you just need to add the other Actions in your controller...
Details
RightsForRole
I think you should use Partial Views.
You can achieved the multiple form inside one form by only using three different Pages(Actions) and use tab as Actionlink. On the Actionlink you call the respective Action.
In your case there will be problem when you will post the form.
Otherwise you should use JQuery to achieve this situation.

Get data element from partial in modal, set value of textbox in parent with Javascript?

I'm using ASP.Net MVC 5 with C#. I have a view with a button that calls a modal, which is populated by a partial view. The partial view runs a foreach loop to display a name, email, and "Select" button from a database of contacts. I want this select button to set the value of an uneditable textbox in the parent view. Upon clicking the "Select" button in this modal, I want the modal to close, and the ID from "data-contact" should populate a textbox in the parent view. I'm not very experienced with Javascript or Jquery.
Partial View
<table class="table table-striped table-hover table-responsive table-condensed">
<tr>
<th>
#Html.Label("First Name")
</th>
<th>
#Html.Label("Last Name")
</th>
<th>
#Html.Label("Email")
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.F_name)
</td>
<td>
#Html.DisplayFor(modelItem => item.L_name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email_1)
</td>
<td>
<button data-contact="#item.Scholarship_contactID" class="btn btn-default" data-dismiss="modal" onclick="javascript:onButtonClick(); return false;">Select</button>
</td>
</tr>
}
</table>
Javascript
<script type="text/javascript">
$(document).ready(function () {
function onButtonClick() {
var contact_id = document.getAttribute.data('contact');
$('#copyto').val(contact_id);
}
});
</script>
And the modal code in the parent view looks like
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Select a Contact:
</div>
<div class="modal-body">
#Html.Partial("ContactPartial", Model.partialModel)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The textbox I want to be populated with the #item.Scholarship_contactID has the following code
<div class="form-group">
#Html.LabelFor(model => model.Scholarship_contactID, new { #class = "control-label col-md-2" })
<div class="col-md-2">
#Html.TextBoxFor(model => model.Scholarship_contactID, "", new { #class = "form-control", #placeholder = "Please select a contact", #id = "copyto", #readonly="readonly" })
#Html.ValidationMessageFor(model => model.Scholarship_contactID, null, new { #class = "help-inline" })
</div>
</div>
The modal displays the partial view (with some formatting errors, but I'll tackle this separately later), but clicking on "Select" will only close out the modal without populating the textbox that I need. Can someone help me with the Javascript here? Again, I'm not a long time Javascript user, so I apologize if I'm missing something simple or using the wrong approach.
Thanks.
The onButtonClick function should be outside the $(document).ready(...) to be accessed. It's because of the scope of the onButtonClick function, it can be accessed only in the scope created by the $(document).ready(...) function.

Categories

Resources