bind a table on click event of button - asp.net-mvc

I am working with ASP.NET MVC 3 Razor. I have a list method in controller, so want to bind this list to table on click event of a button. How will I achieve this functionality.
Here is my controller method:
public ActionResult getItnList(string scanCode)
{
List<List<String>> getitnDetails_List = getitnDetails(date, name);
ViewBag.getitnDetails = getitnDetails_List;
return Json(new { getitnDetails_List = getitnDetails_List }, JsonRequestBehavior. AllowGet);
}
Here is my view code:
#{
List<List<String>> str = (List<List<String>>)ViewBag.getitnDetails;
}
<table id="list" width="100%">
<td><b>Harvest Date</b></td>
<td><b>Product</b></td>
#for (int i = 0; i <= str.Count - 1; i++)
<td>#str[i][0].ToString()</td>
<td>#str[i][1].ToString()</td>
</table>
How will I bind this table to list on click event of button?

I'm not exactly sure what you are asking. But if you want to get the list on the click of a button you can use jQuery .getJSON (http://api.jquery.com/jQuery.getJSON/) to retrieve the list data and then insert it with javascript. Or you could render the list in the action and simply use json .get and insert the result.

Try this
View
<table>
<tr>
<th>
Name
</th>
<th>
PhoneNo
</th>
<th>
Address
</th>
<th>
Action
</th>
</tr>
#{var list = ViewBag.RegisterItems; }
#if (list != null)
{
foreach (var m in list)
{
<tr>
<td>
<input id="txtName-#m.ID.ToString()" type="text" class="hide" value="#m.Name.ToString()"/>
</td>
<td>
<input id="txtPhoneNo-#m.ID.ToString()" type="text" class="hide" value="#m.PhoneNo.ToString()"/>
</td>
<td>
<input id="txtAddress-#m.ID.ToString()" type="text" class="hide" value="#m.Address.ToString()"/>
</td>
</tr>
}
}
</table>
Controller
public ActionResult CustomerInfo()
{
ViewBag.RegisterItems = GetAllRegisterData();
return View();
}

Related

how to pass two values in a form inside a table row to the controller ? Razor

How can I make this table
<table class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>
Name
</th>
<th>
Price
</th>
<th>
Quantity
</th>
<th>
Options
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Items)
{
<tr>
<td>#item.Name</td>
<td>#item.Price</td>
<td><input type="number" name="Quantity"/> </td>
<td><input type="submit" class="btn btn-primary" value="Add" /></td>
</tr>
}
</tbody>
</table>
To work like the table below (this one works fine)
<table class="table table-bordered table-striped" style="width:100%" >
<thead>
<tr>
<th>
Name
</th>
<th>
Prrice
</th>
<th>
Quantity
</th>
<th class="text-center">
Options
</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<td width="55%">#item.Name</td>
<td width="10%" class="text-right">#item.Price $</td>
<td width="10%" class="text-right">#item.Quantity</td>
<td width="25%">
<div class="w-100 btn-group"role="group">
<a asp-controller="item" asp-action="Update" asp- asp-route-Id="#item.Id" class="btn btn-outline-primary mx-1">Update</a>
<a asp-controller="item" asp-action="Delete" asp-route-Id="#item.Id" class="btn btn-outline-danger mx-1">Delete</a>
</div>
</td>
</tr>
}
</tbody>
</table>
I want to pass the item.quantity and item.id to the controller.
Item model
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public float Price { get; set; }
public int Quantity { get; set; }
}
I found that you can put each item in a table and a form for each one Post, but I would like to know if with asp.net it can be made simpler
If you need to post ALL ROW VALUES (assuming each row is a different object) then use a form outside the table and take needed properties into inputs in order to get posted.
If you need to post SINGLE ROW VALUES (only submit the row where the value is beign modified) then you could write some JS and make a post or ajax post of all inputs in the current row.
$(document).on('keypress', 'input[data-ajax="row"]', function (e) {
if (e.keyCode !== 13) {
return;
}
var self = $(this);
var row = self.closest('tr');
var url = '/controller/action';
var propertyNames = new Array();
var propertyValues = new Array();
row.find('input[data-ajax="row"]').each(function () {
$(this).attr('readonly', 'readonly');
propertyNames.push($(this).attr('id'));
propertyValues.push($(this).val());
});
$.ajax({
url: url,
type: 'POST',
data: { propertyNames, propertyValues },
success: function (data) {
//SUCCESS CODE HERE (reload)
},
error: function (data) {
console.log('error');
alert('error');
}
});
return;
});
Note that you will need to add data-ajax="row" attribute to your input. Alsou you could remove the dynamic code and find all needed controls inside the row scope.
Ej: var name = row.find('#name').val()

Cannot convert type 'char' to 'string

I am getting this error in one project and the code works perfectly fine on another project. I have tried multiple to duplicate the code as it is. Is there a way to find where the error originated from??
#if (ViewBag.RolesForThisUser != null)
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
#Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
#foreach (string s in ViewBag.RolesForThisUser) //this line
{
<li>#s</li>
}
</td>
</tr>
</table>
I suspected ViewBag.RolesForThisUser itself already contains a string, neither an array nor collection of strings (e.g. string[] or List<string>), hence using foreach loop is pointless (and string itself contains char[] array which explains why type conversion failed). You can simply display it without foreach:
#if (!string.IsNullOrEmpty(ViewBag.RolesForThisUser))
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
#Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
#ViewBag.RolesForThisUser
</td>
</tr>
</table>
</div>
}
Or assign a string collection to ViewBag.RolesForThisUser from GET method so that you can use foreach loop, like example below:
Controller
public ActionResult ActionName()
{
var list = new List<string>();
list.Add("Administrator");
// add other values here
ViewBag.RolesForThisUser = list;
return View();
}
View
#if (ViewBag.RolesForThisUser != null)
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
#Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
#foreach (string s in ViewBag.RolesForThisUser)
{
<p>#s</p>
}
</td>
</tr>
</table>
</div>
}

ASP.NET MVC CheckBox List sending always null

I want to create a table with items and checkboxes to select these items. I am including these checkboxes in a list but this list is always returning null. Thank you very much for your help.
Controller:
public ActionResult Index()
{
var expenseTypesView = new ViewExpenseTypesAndSelection
{
ExpensesTypes = _context.ExpenseType.ToList(),
};
return View(expenseTypesView);
}
[HttpPost]
public ActionResult SelectExpensesTypes( ViewExpenseTypesAndSelection SelectedExpenses)
{
var entry = new userSpecificExpenses();
var i = 0;
foreach (var item in SelectedExpenses.SelectedExpenses)
{
if(item)
{
entry.expenseTypeId = i;
entry.UtilisateurId= User.Identity.GetUserId();
_context.UserspecificExpenses.Add(entry);
_context.SaveChanges();
}
i++;
}
return View();
}
View:
#model MBT.ViewModels.ViewExpenseTypesAndSelection
....
#using (Html.BeginForm("SelectExpensesTypes", "ExpenseTypes"))
{
<table class="table table-bordered table-hover">
<thead>
<tr>
<th class="text-center">Expense</th>
<th class="text-center">Include</th>
</tr>
</thead>
<tbody>
#{
for (int i = 0; i < Model.ExpensesTypes.Count; i++)
{
<tr>
<td>
<div class="checkbox">
#Model.ExpensesTypes[i].Type
</div>
</td>
<td>
<div class="checkbox">
#Html.CheckBoxFor(m => m.SelectedExpenses[i])
</div>
</td>
</tr>
}
}
</tbody>
</table>
<button type="submit" class="btn btn-primary">Submit</button>
}
You sending ViewExpenseTypesAndSelection almost null just with ExpensesTypes and then post it back to your post method. It means you send null and receive null.
So what is wrong with that?

Pass Table Value from View to Controller MVC

Can I pass table td values to controller?
View strongly typed:
#using (Html.BeginForm("PostClick", "Vendor", FormMethod.Post)) {
<table class="tblData">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().SubmittedDate)
</th>
<th>
#Html.DisplayNameFor(model => model.First().StartDate)
</th>
</tr>
<tr>
<td>
#Html.DisplayFor(modelItem => item.SubmittedDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartDate)
</td>
</tr>
</table>
<input type="submit" value="submit" />
}
Contoller code:
public void PostClick(FormCollection collection)
{
/*Some Code */
}
How to pass table value from view to controller?
Have used JasonData & Ajax call and able to send the table data to controller.
Want to know any other method can be done because FormCollection data not able to find table values
Your need to generate controls that post back (input, textarea or select) and generate those controls in a for loop (or use a custom EditorTemplate for type Vendor)
View
#model List<Vendor>
#using (Html.BeginForm())
{
<table class="tblData">
<thead>
....
</thead>
<tbody>
for(int i = 0; i < Model.Count; i++)
{
<tr>
<td>#Html.TextBoxFor(m => m[i].SubmittedDate)</td>
<td>#Html.TextBoxFor(m => m[i].StartDate)</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="submit" />
}
Post method
public void PostClick(List<Vendor> model)
{
/*Some Code */
}

How to display list items in view passed from the controller ?

I am developing MVC app.
I want to create the list in the controller and pass it to the view.
I have written the method in the controller but dont know how to call it form view and display the value which it return.
Method in controller.
public List<Invoice> GetInvoiceList(int Pid)
{
List<Invoice> Invoices = new List<Invoice>();
var InvoiceList = (from i in db.Invoices
where i.PaymentAdviceId == Pid
select i);
Invoices = InvoiceList.ToList();
return (Invoices);
}
View Code
<div class="row-fluid">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Advice No
</th>
<th>
Invoices
</th>
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>
#Html.DisplayFor(modelItem => item.AdviceNo)
</td>
I wan to call the controller method GetInvoiceList here and
want to display list items here...
<td>
</tr>
</tbody>
Add a PartialView to your project that has it's model set to List<Invoice>
then modify your code:
public PartialViewResult GetInvoiceList(int Pid)
{
List<Invoice> Invoices = new List<Invoice>();
var InvoiceList = (from i in db.Invoices
where i.PaymentAdviceId == Pid
select i);
Invoices = InvoiceList.ToList();
return PartialView("partialViewName", Invoices);
}
in your other view:
<tr>
<td>
#Html.DisplayFor(modelItem => item.AdviceNo)
</td>
<td> #Html.Action("GetInvoiceList", new {Pid = item.id})</td>
</tr>

Resources