C#, MVC4
I have a PartialView created for a popup data entry on a form. This is a snippet from the main form.
<input type="button" id="btnAddGroup" value="Add Group" />
<p>
<input type="submit" value="Save" />
</p>
</div>
</fieldset> }
I discovered quickly that I needed to have the line:
#Html.Partial("_Groups")
Outside the primary view so the form submit button in the partial view would accept and process.
My controller processes and sends back the data using:
return PartialView(NewModel);
I can run the debugger and see that the data is getting passed back to the PartialView but since the view sits outside the original form, it's not displaying.
My PartialView is as follows:
#model OMD.ViewModels.SearchedUser
#if (Model.AddGroups != null)
{
<h2>Groups to be Added</h2>
<table id="AddGroupList">
<thead>
<tr>
<th>
Name
</th>
<th>
Until
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
#foreach (var Group in Model.AddGroups)
{
<tr>
<td>
#Html.DisplayFor(model=> Group.GroupName)
</td>
<td>
#Html.DisplayFor(model=> Group.dtAddedTo)
</td>
<td>
#Html.DisplayFor(model=> Group.bAddOrRemove)
</td>
<td>
#if (AuthCheck.CheckUser(new HttpContextWrapper(HttpContext.Current), oRoles.StaffChangeRequest) ||
AuthCheck.CheckUser(new HttpContextWrapper(HttpContext.Current), oRoles.StudentChangeRequest))
{
<span>#Html.ActionLink("Remove", "RemoveGroup", new { id = Group.ID })</span>
}
</td>
</tr>
}
</tbody>
</table>
}
<div id="dlgAddGroup" title="Add Group" style="display: none">
#using (Ajax.BeginForm("_Groups",new AjaxOptions { UpdateTargetId ="ID",OnSuccess="onSuccess"}))
{
#Html.DropDownListFor(model => model.AllGroups,new SelectList(Model.AllGroups, "ID","GroupName"), "Select Group to Add")
#Html.ValidationMessageFor(model => model.AllGroups)
<div class="editor-label">
#Html.CheckBox("cbxMakeGroupPermanent", true) Permanent
</div>
<div class="editor-label" id ="dlgUntil1">
Group Add Until:
</div>
<div class="editor-field" id="dlgUntil2">
#Html.TextBox("tbAddUntil",null,new { maxlength = 30, style = "width: 100px" })
<span style='padding:5px'><img id='calImageGroup' alt="img" src='~/Images/calendar.gif'></span>
</div>
<button class="btn btn-inverse" type="submit">add</button>
}
I can see the table at the top display the information posted back to it but it doesn't show on the screen...
How can I get this data/table to display?
Related
I am trying to render a view in a modal but I can't figure out how to do this.
I tried a workaround by creating a partial view but could not trigger a method in the home controller (on load form).
I was wondering, is it possible to have a partial view triggering a method in the controller or should I changed it to a casual view (which I did not manage to show it)?
view:
#model IEnumerable<CharityProject.Models.UserInfos>
#{
ViewData["Title"] = "SelectAddress";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Select Address</h2>
<p>
#* <input type="button" value="Add New Address" onclick="location.href='#Url.Action("Create", "UserInfos")'" />*#
<input type="button" data-toggle="modal" data-target="#myModal" value="Add New Address" class="btn btn-default">
</p>
<div class="row">
<div class="col-md-6">
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Cities)
</th>
<th>
#Html.DisplayNameFor(model => model.Area)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.POB)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNo)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNo2)
</th>
<th>
#Html.DisplayNameFor(model => model.IsDefault)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Cities.CityName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Area)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.POB)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNo2)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsDefault)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="col-md-6">
</div>
</div>
<div class="modal fade" id="myModal" 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" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
**#{await Html.RenderPartialAsync("CreateAddress", new UserInfos());}**
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" uiactions="#Url.Action("Create", "UserInfos")" formmethod="post">Save changes</button>
</div>
</div>
</div>
</div>
Home controller:
public ActionResult CreateAddress()
{
return View();
}
I haven't used ,Net Core as of yet, still in the learning process, but from what I remember from the classic MVC approach(.NET),
Create a an AJAX method that will send data to the controller using
#Html.Action/#Html.ActionLink/#Url.Action, etc
The partial View should have access to the main view's Model object ( if you do a #Html.Partial)
If you are using ASP.NET Core you should use View Components.
Create a class deriving from ViewComponent containing the InvokeAsync method:
public class AddressViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
Put your view in this path structure "/Views/Shared/Components/Address/Default.cshtml".
Then, to render the component in your modal:
<div class="modal-body">
#await Component.InvokeAsync("Address")
</div>
I have a quick question. I have a form with a for loop. Each for loop has a text box. I want to have two buttons that when I click on one, all the text boxes get populated with the value in the button. For example, when I click on the button "Add 50 minutes," I want all my text boxes to populate with 50. The same goes for if I click on the button "Add 110 minutes" (Screen shot attached)
Here is my form
#using (Html.BeginForm("Index", "Minutes", FormMethod.Post, new { enctype = "multipart/form-date", onsubmit = "popup()" }))
{
#Html.ValidationSummary(true)
<fieldset>
<div>
<table id="tablereport" class="table table-striped table-bordered table-hover table-condensed">
<thead style="background-color:black; font-weight:bold; color:aliceblue">
<tr>
</thead>
<tr>
<td><b>#Html.Label("Date :")</b></td>
<td>#Html.TextBox("datepicker", DateTime.Now.ToString("MM/dd/yyyy"), new { required = "required" })</td>
</tr>
<tr>
<td><input type="button" id="btnSetText" value="Add 50 Minutes" class="btn btn-default" onclick="setText" /></td>
<td><input type="button" value="Add 110 Minutes" class="btn btn-default" /></td>
</tr>
</table>
</div>
#if (ViewBag.Message != null)
{
<div id="dialog-message" title="Alert !!">
<p>
<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
#ViewBag.Message
</p>
</div>
}
<table id="tablereport" class="table table-striped table-bordered table-hover table-condensed">
<thead style="background-color:black; font-weight:bold; color:aliceblue">
<tr>
</thead>
<tr>
<th>Class ID</th>
<th>Course Title</th>
<th>Department</th>
<th>SID</th>
<th>Full Name</th>
<th>Minutes</th>
</tr>
#for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model[i].ClassID)
#Html.HiddenFor(model => model[i].ClassID)
</td>
<td>
#Html.DisplayFor(model => model[i].CourseTitle)
#Html.HiddenFor(model => model[i].CourseTitle)
</td>
<td>
#Html.DisplayFor(model => model[i].Department)
#Html.HiddenFor(model => model[i].Department)
</td>
<td>
#Html.DisplayFor(model => model[i].SID)
#Html.HiddenFor(model => model[i].SID)
</td>
<td>
#Html.DisplayFor(model => model[i].FullName)
#Html.HiddenFor(model => model[i].FullName)
</td>
<td>
#Html.TextBoxFor(model => model[i].Minutes, new { #Value = "0" })
#Html.ValidationMessageFor(model => model[i].Minutes)
</td>
</tr>
}
</table>
<table align="center">
<tr>
<td><input type="submit" value="Save" class="btn btn-default" onclick="popup()" /></td>
</tr>
</table>
</fieldset>
}
Here is my script
<script>
var date = new Date();
var maxdate = date.getDate();
//var currentDate = $(".selector").datepicker("getDate");
$(function () {
$("#datepicker").datepicker({
defaultDate: maxdate,
minDate: '-1M',
maxDate: '+0D'
});
});
**function setText(){
var setText = document.getElementById('setText');
setText.value = '50';
}**
The script I have is working, but will only populate one text box.
Thank you!!
Well the ids should be unique for every element in the DOM. Even though in your case there's more than one element with the same id the document.getElementById() function returns one element(the first one with that id). What you want to do is add a class to each textbox and then use document.getElementsByClassName() which will return a list of all the elements that have the class.
For example:
$("#add-50").on('click', function() {
// ill intentionally use vanilla js here
var inputs = document.getElementsByClassName('textbox');
for (var i = 0; i < inputs.length; i++) {
var input1 = inputs[i];
input1.value = '50';
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="add-50">Click Me for 50</button><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" />
</div>
You can wrap all the textboxes in a div, add a class to all of them and then use something like this:
function setValue(value){
$('#divWithtextboxes .TextboxClass').each(function (i) {
$(this).val(value);
<br>
});<br>
Hi Everyone, I try to used the modal to avoid having multiple pages. but I got a problem, first, I click the view button and it will display to modal the right information; but when I click other view button instead the next data, it display the previous data.
second, after I select the view button and try to select the new shoes button (expectation must be display the new module in modal) it display the data of the previous item I select in view button:
Controller:
public ActionResult Index() //main page
{
var result = _Context.Shoeses.Include(x => x.Supply).ToList();
return View(result);
}
public ActionResult New() //create new product
{
var SupplierCategory = _Context.Suppliers.ToList();
var listOfSupplier = new ShoesViewModel
{
Supply = SupplierCategory
};
return PartialView(listOfSupplier);
}
public ActionResult Details(int id) //view selected data
{
Shoes productItem = new Shoes();
productItem = _Context.Shoeses.Find(id);
return PartialView("_Details", productItem);
}
View: Index
#model IEnumerable<ShoeInformation.Models.Shoes>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<h2>Tindahan sa Bahay ni Tatang Benjamin</h2>
<br />
<br />
//my modal
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 class="modal-title">Details</h3>
</div>
<div class="modal-body" id="modalBody">
Testing Only
</div>
</div>
</div>
</div>
//my modal
<p>#Html.ActionLink("New Shoes", "New", "Shoes", new { id="btn_Modal"}, new { #class = "btn btn-primary btn-lg",#data_toggle="modal" ,#data_target="#myModal"})</p>
<table class="table table-striped table-hover ">
<tr>
<th>Product ID
</th>
<th>Product Code
</th>
<th>Product Name
</th>
<th>Item Size
</th>
<th>Supplier
</th>
<th>Available Quantity
</th>
<th>Unit Price (Php)
</th>
<th>Action
</th>
</tr>
#foreach (var shoes in Model)
{
<tr class="success">
<td>
#shoes.Id
</td>
<td>
#shoes.ProductCode
</td>
<td>
#Html.ActionLink(#shoes.ProductName, "Edit", "Shoes", new { id=shoes.Id})
</td>
<td>
#shoes.ItemSize
</td>
<td>
<input type="hidden" value="#shoes.Id" id="hiddenval" />
#Html.HiddenFor(x => shoes.Id)
#Html.DisplayFor(x => shoes.Supply.SupplierName)
</td>
<td>
#shoes.ItemQty
</td>
<td>
#shoes.ItemUnitPrice
</td>
<td>
#Html.ActionLink("View", "Details", "Shoes", new { id=shoes.Id}, new { #class = "view-Modal",#data_toggle="modal" ,#data_target="#myModal"})
</td>
</tr>
}
</table>
#*Open Modal Testing*#
#section scripts
{
<script src="~/Scripts/jquery.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#myModal').hide();
$("#btn_Modal").click(function () {
$('#myModal').modal('show');
});
$(".view-Modal").click(function () {
var productId =
$(this).closest('tr').find('#hiddenval').val();
$.ajax({
type: 'POST',
url: '/Shoes/Details',
data: { id: productId },
success: function (response)
{
$('#modalBody').html(response);
$('#myModal').modal('show');
}
});
})
$(".close").click(function ()
{
console.log("Clear All");
});
});
</script>
}
partial view: _details
#model ShoeInformation.Models.Shoes
<div>
<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">Details</h4>
</div>
<div class="modal-body">
<table class="tablemodel">
<tr>
<tr>
#Html.DisplayFor(x=>x.Id)
</tr>
<tr>
#Html.DisplayFor(x=>x.ProductName)
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
I try to breakpoint to see the problem but everything is working properly, however in the modal it display the same value
can someone please help me regarding to this matter
thanks in advance
I am a novice in asp.net and i want create simple database application.
I need pass parameters between view and controller to retrieve data from database.
i need only this data which title is "something". I create simple left menu which contains search settings.
This is my view page.
#model IEnumerable<TwojaBiblioteka.Models.Ksiazka>
#{
ViewBag.Title = "Home Page";
}
#Styles.Render("~/Content/css")
<div class="jumbotron">
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-2">
<h2>Szukaj</h2>
<div class="textboxes">
<input type="text" name="Tytul" class="form-control" id="Tytul" placeholder="Tytuł..." />
<input type="text" name="txtAutor" class="form-control" id="txtAutor" placeholder="Autor..." />
<input type="text" name="txtISBN" class="form-control" id="txtISBN" placeholder="ISBN..." />
</div>
<center>
#Ajax.ActionLink("Szukaj", "SzukajKsiazki", new AjaxOptions()
{
HttpMethod="GET",
UpdateTargetId= "divKsiazki",
InsertionMode= InsertionMode.Replace
})
</center>
</div>
<div id="divKsiazki"class="col-md-10 ">
</div>
</div>
</div>
</div>
This is view for display data from database:
#model IEnumerable<TwojaBiblioteka.Models.Ksiazka>
<table class="table" style="border:1px solid black;">
<tr>
<th>
#Html.DisplayNameFor(model => model.Tytul)
</th>
<th>
#Html.DisplayNameFor(model => model.Autor)
</th>
<th>
#Html.DisplayNameFor(model => model.ISBN)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tytul)
</td>
<td>
#Html.DisplayFor(modelItem => item.Autor)
</td>
<td>
#Html.DisplayFor(modelItem => item.ISBN)
</td>
</tr>
}
</table>
And this is my controller:
public PartialViewResult SzukajKsiazki()
{
string tytul="something";
var ksiazkilist = db.Ksiazka.Where(x => x.Tytul == tytul).ToList();
return PartialView("_ListaKsiazek",wypozyczone);
}
So how i can pass data from my textboxes to controller to display only those records which contains textbox text?
Your controller action should accept a parameter. In Asp.Net MVC, it is normal for this to be the model:
public PartialViewResult SzukajKsiazki(IEnumerable<TwojaBiblioteka.Models.Ksiazka> model)
Your view should have all of the editor elements from the model enclosed in a form and you need a submit button:
#using (Html.BeginForm("SzukajKsiazki", "ControllerName", FormMethod.Post)
{
<table class="table" style="border:1px solid black;">
<tr>
<th>
#Html.DisplayNameFor(model => model.Tytul)
</th>
<th>
#Html.DisplayNameFor(model => model.Autor)
</th>
<th>
#Html.DisplayNameFor(model => model.ISBN)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tytul)
</td>
<td>
#Html.DisplayFor(modelItem => item.Autor)
</td>
<td>
#Html.DisplayFor(modelItem => item.ISBN)
</td>
</tr>
}
</table>
<input type="submit" value="submit">
}
I am trying to pass values from a view to a controller in MVC. I am using a ViewModel and normally the values would bind to the properties as long as the names are the same. However because the values are generated via a foreach loop the names of the values do not match the names of the properties in the view model.
I am working around this by assigning the values to a variable in Razor. However one of my values is in a text box on the form and the value is not being passed to the controller and I cannot work out why.
I get a null exception when clicking the button.
VIEW Code is below:
#model PagedList.IPagedList<Mojito.Domain.ViewModels.ShoppingCartProductItem>
#using System.Web.UI.WebControls
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Mojito Products</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().Description)
</th>
<th>
#Html.ActionLink("Price", "Index", new { sortOrder = ViewBag.SortByPrice, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().Quantity)
</th>
<th>
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Quantity)
</td>
<td>
#{string Description = item.Description;}
#{decimal Price = item.Price;}
#{int Quantity = item.Quantity; }
#using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
{
<div class="pull-right">
#if (Request.Url != null)
{
<input type="text" hidden="true" name="Description" value=#Description />
<input type="text" hidden="true" name="Price" value=#Price />
<input type="text" hidden="true" name="Quantity" value=#Quantity />
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-success" value="Add to cart" />
}
</div>
}
</td>
</tr>
}
</table>
<div class="col-md-12">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
</div>
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
Controller Code below
public ActionResult AddToCart(Cart cart, MojitoProduct product, string returnUrl, int Quantity =1)
{
if (product != null)
{
cart.AddItem(product, Quantity);
}
return RedirectToAction("Index", new { returnUrl });
}
Do not use foreach. Use a for-loop instead and within this, qualify the full path to your properties using the index.
Better yet: use a Edit- or DisplayTemplate for the ShoppingCartProductItem. This will also keep your path.
You have to use for loop instead of foreach:
#for (int i=0;i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model[i].Description)
</td>
<td>
#Html.DisplayFor(modelItem => Model[i].Price)
</td>
<td>
#Html.TextBoxFor(modelItem => Model[i].Quantity)
</td>
..........................
..........................
..........................
}
you can also post all using one form by posting List<ShoppingCartProductItem>, see Model Binding To A List
Your textboxes so values out of the form.
Try like below
#using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
{
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Quantity)
</td>
<td>
#{string Description = item.Description;}
#{decimal Price = item.Price;}
#{int Quantity = item.Quantity; }
<div class="pull-right">
#if (Request.Url != null)
{
<input type="text" hidden="true" name="Description" value=#Description />
<input type="text" hidden="true" name="Price" value=#Price />
<input type="text" hidden="true" name="Quantity" value=#Quantity />
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-success" value="Add to cart" />
}
</div>
</td>
</tr>
}
}
I resolved this in the short term by using new and forcing the name of the parameter.
#Html.HiddenFor(modelItem => t.NoOfUsers, new { Name = "NoOfUsers", id = "NoOfUsers" })