I want to serialize form data using jquery - c#

Hello guys i working on data serialize using jquery
i have pasted my HTML code below.
HTML
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="ibox-content">
<form id="product">
<table class="table">
<thead>
<tr>
<th>Action</th>
<th>Product Name</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
#foreach (var _product in Model.ProductList)
{
<tr>
<td>Details</td>
<td>
<strong>
#_product.name
<input type="hidden" name="productId" value="#_product.productId" />
</strong>
</td>
<td id="price">#_product.wholesalePrice</td>
<td id="quantity"><input style="width:50px;" name="qty" value="0"><input type="hidden" name="total" id="rowTotal" /></td>
<td id="value"></td>
</tr>
}
</tbody>
</table>
</form>
<div class="ibox-content">
<button id="totalCal" class="btn btn-primary pull-right">Calculate</button>
</div>
<table class="table invoice-total">
<tbody>
<tr>
<td><strong>Sub Total :</strong></td>
<td id="result">$1026.00</td>
</tr>
<tr>
<td><strong>Shipping :</strong></td>
<td id="Shipping">$235.98</td>
</tr>
<tr>
<td><strong>TOTAL :</strong></td>
<td id="finalTotal">$1261.98</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Jquery function
function GetTblRow() {
var data = $("#product").serializeArray();
var from = JSON.stringify(data);
console.log(from);
};
Output
[{"name":"productId","value":"1"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"2"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"3"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"4"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"5"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"6"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"7"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"8"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"9"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"10"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"12"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"13"},{"name":"qty","value":"0"},{"name":"total","value":"0"}]
Expected Output
[{"ProductId":"1","qty":"0","total":"0"},"ProductId":"1","qty":"0","total":"0"},{"ProductId":"2","qty":"0","total":"0"},{"ProductId":"3","qty":"0","total":"0"},{"ProductId":"4","qty":"0","total":"0"}]
i did above code for serialize form data but i can not get above expected output. So can you help me with this?

you cannot directly use serializeArray() to get the expected json you have to separate the expected result from array
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$("#totalCal").click(function(){
alert(JSON.stringify($('#product').serializeObject()));
return false;
});
});
</script>

You can use some custom code to format your array. Here is the simplest solution:
function getFormattedArray(array){
var result = [];
for(var currentPosition = 0;currentPosition < array.length; currentPosition += 3) {
result.push({ProductId: array[currentPosition].value,
qty: array[currentPosition+1].value,
total: array[currentPosition+1].value});
}
return result;
}

Related

Row to send a List<Object> from Razor page to Update?

I need to send a List back to my controller and update the values on my repository.
But after load the view with the values, update it and click the submit button, I don't know how to get the list with the update values and call the update method from the repository.
I'm using .Net 4.7.2.
HomeController:
[HttpGet]
public ActionResult Nota(string Concurso)
{
List<InscricoesModel> model = new List<InscricoesModel>();
InscricoesRepository repository = new InscricoesRepository();
model = repository.GetAprovadosPrimeiraFase(new Guid(Concurso));
return View("Nota",model);
}
[HttpPost]
public void UdateNotas(List<InscricoesModel> model)
{
InscricoesRepository repository = new InscricoesRepository();
foreach(InscricoesModel item in model)
{
repository.Update(item);
}
}
Nota.cshtml:
#model List<ConcursoBolsaSegundaFase.Model.InscricoesModel>
<h1>Classificados 2ª Fase</h1>
<hr />
<p>Exportado em #DateTime.Now</p>
<div style="margin-top:15px">
#* TABELA RESULTADO *#
<div id="notasAprovadosSegundaFase" style="margin-top:10px">
#using (Html.BeginForm("UdateNotas", "Home", Model, FormMethod.Post))
{
<table class="table table-bordered" id="tblNotaAprovadosSegundaFase">
<thead>
<tr>
<th>Inscrição</th>
<th>Nome</th>
<th>Nota Primeira Fase</th>
<th>Fez Carta</th>
<th>Nota Segunda Fase</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var linha in Model)
{
<tr>
<td>#linha.Inscricao</td>
<td>#linha.Nome</td>
<td>#linha.NotaPrimeiraFase</td>
<td>
<select>
<option value="false">Não</option>
<option value="true">Sim</option>
</select>
</td>
<td><input type="text" value="#linha.NotaSegundaFase"></td>
</tr>
}
}
</tbody>
</table>
<button type="submit" class="btn btn-success">Salvar</button>
}
</div>
</div>
The UpdateNotas method in my controller never recive a value, i don't know how to send the list from the view to my controller.
In MVC, the name of the input will be binded to the variable in the controller. In your case, your input has no name. I suggest you look at the html helpers.
This would bind your values properly.
for (int i = 0;i<Model.Count;i++)
{
Html.TextBoxFor(model => Model[i].NotaSegundaFase)
}
In this case, only NotaSegundaFase would be sent back to the controller.
You can use #Html.HiddenFor() to hold the data on the view and bind to controller on Post.
#using (Html.BeginForm("UdateNotas", "Home", Model, FormMethod.Post))
{
<table class="table table-striped table-bordered table-sm table-responsive">
<thead>
<tr>
<th>Inscrição</th>
<th>Nome</th>
<th>Nota Primeira Fase</th>
<th>Fez Carta</th>
<th>Nota Segunda Fase</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(model => Model[i].Inscrição)
#Html.HiddenFor(model => Model[i].Nome)
#Html.HiddenFor(model => Model[i].NotaPrimeiraFase)
<tr>
<td>#Model[i].Inscrição</td>
<td>#Model[i].Nome</td>
<td>#Model[i].NotaPrimeiraFase</td>
#*do this similary for other property *#
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-success">Salvar</button>
}
As far as I understood,you want to post DropDownList value only.
if you decide to update other fields just add the Html.Editor into the loop like following.
#Html.Editor("[" + i + "].Inscricao")
#Html.Editor("[" + i + "].Nome")
I hope this will help.
#using (Html.BeginForm("UdateNotas", "Home", Model, FormMethod.Post))
{
<table class="table table-bordered" id="tblNotaAprovadosSegundaFase">
<thead>
<tr>
<th>Inscrição</th>
<th>Nome</th>
<th>Nota Primeira Fase</th>
<th>Fez Carta</th>
<th>Nota Segunda Fase</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>#Model[i].Inscrição</td>
<td>#Model[i].Nome</td>
<td>#Model[i].NotaPrimeiraFase</td>
<td>
<select name="[#i].NotaSegundaFase">
<option value="false">Não</option>
<option value="true">Sim</option>
</select>
</td>
<td><input type="text" value="#linha.NotaSegundaFase"></td>
</tr>
}
}
</tbody>
</table>
<button type="submit" class="btn btn-success">Salvar</button>
}
Note : don't change anything in the controller. model binder should resolve everything from the request.

How to bind the multiple radio button values to controller action

following is my view code, I pass list from controller to view and here I am iterating that list through foreach I want to pass the same view-model list to the action when I submit the form
#model IEnumerable<AskQuestionViewModel>
.
.
.
<table class="table table-bordered">
<thead>
<tr>
<td>Question</td>
<td>Yes</td>
<td>No</td>
</tr>
</thead>
<tbody>
#foreach (var q in Model)
{
<tr>
<td>#q.Question</td>
#if (q.Answer == true)
{
<td><input type="radio" name="#q.QuestionID" value="true" checked />/td>
}
else
{
<td><input type="radio" name=#q.QuestionID value="true" required /></td>
}
#if (q.Answer == false)
{
<td><input type="radio" name=#q.QuestionID value="false" checked /></td>
}
else
{
<td><input type="radio" name=#q.QuestionID value="false" required /></td>
}
</tr>
}
The following is action code
[HttpPost]
public ActionResult AskQuestions(List<AskQuestionViewModel> askQVM)
{
...
}
I'm getting null in askQVM
This is what you need for postback.
<table class="table table-bordered">
<thead>
<tr>
<td>Question</td>
<td>Yes</td>
<td>No</td>
</tr>
</thead>
<tbody>
#using (Html.BeginForm("AskQuestions", "Questions", FormMethod.Post))
{
for (int i = 0; i < Model.Count; i++)
{
var yesOptions = Model[i].Answer ? new { #checked = "checked" } : null;
var noOptions = Model[i].Answer ? null : new { #checked = "checked" };
<tr>
<td>
#Model[i].Question
#Html.HiddenFor(model=>Model[i].QuestionID)
#Html.HiddenFor(model=>Model[i].Question)
</td>
<td>#Html.RadioButtonFor(model => Model[i].Answer, true, yesOptions)</td>
<td>#Html.RadioButtonFor(model => Model[i].Answer, false, noOptions)</td>
</tr>
}
<button type="submit">Submit</button>
}
</tbody>
</table>

Asp.net jQuery works outside, but not inside foreach loop

This is the script I am working with.
$(document).ready(function () {
$('#selectall').click(function () {
$('.selectedId').prop('checked', isChecked('selectall'));
});
});
function isChecked(checkboxId) {
var id = '#' + checkboxId;
return $(id).is(":checked");
}
function resetSelectAll() {
// if all checkbox are selected, check the selectall checkbox
// and viceversa
if ($(".selectedId").length === $(".selectedId:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
if ($(".selectedId:checked").length > 0) {
$('#edit').attr("disabled", false);
} else {
$('#edit').attr("disabled", true);
}
}
And this is the cshtml view.
<table id="notificationsTableId">
<thead>
<tr role="row">
<th rowspan="1" colspan="1">
<input type="checkbox" id="selectall" />
</th>
</tr>
</thead>
<tbody>
<tr class="results-table-row odd">
<td>
<input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll();"/>
</td>
</tr>
<tr class="results-table-row even">
<td>
<input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll();"/>
</td>
</tr>
<tr class="results-table-row even odd">
<td>
<input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll();" />
</td>
</tr>
</tbody>
</table>
Right now the select button will work like it should, if i check it it will check all the dates inside that table.
But what I want to do is I want that button to select all the Check-boxes on the page.
But if I give a checkbox the same ID inside my foreach loop like this:
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" id="selectedId" name="isoDate" value="#isoDate"/>#day-#isoDate
</label>
}
It doesn't work, it will still only select those 3 check-boxes on the top of the page. I would assume it would check all the check-boxes correct?
It ends up like this:
You are using selectedId as id instead of class like other checkboxes. Use it as class attribute as shown below
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" class="selectedId" name="isoDate" value="#isoDate"/>#day-#isoDate
</label>
}

`<td>` will be calculated if the display of the `tr` is not none

In my cshtml file, I want the <td> to be calculated if the display of the tr is not none.
<tr id="abc" style="display:none;height: 30px;">
<td class="titleStyle">Page:</td>
<td align="left">#Html.DropDownList(("pages"),
(IEnumerable<SelectListItem>)ViewData["mypages"], new { onchange = "func()",
id = "page2", style = "float:left; width: 276px;height: 20px;" })</td>
so I tried something like:
<script type="text/javascript">
if ($("#abc").css("display") != "none") {
}
</script>
but how can I continue from here?
any help appreciated!
You mean something like this? Using window.getComputedStyle (IE9+)
HTML
<table>
<tbody>
<tr id="abc" style="display:none;height: 30px;">
<td class="titleStyle">Page:</td>
</tr>
<tr id="abcd" style="height: 30px;">
<td class="titleStyle">Page:</td>
</tr>
</tbody>
</table>
Javascript
var trs = document.getElementsByTagName("tr"),
length = trs.length,
i = 0;
while (i < length) {
if (window.getComputedStyle(trs[i]).display !== "none") {
trs[i].children[0].firstChild.nodeValue = "Page: 1";
}
i += 1;
}
On jsfiddle

Knockout.js - cannot get length of array at cannot remove item from array

See code (am using Knockout.js over ASP MVC 3):
#model List<Person>
#{
ViewBag.Title = "Home Page";
}
<table>
<thead><tr>
<th>First Name</th><th>Last Name</th><th>Age</th><th>Department</th> <th></th>
</tr></thead>
<tbody data-bind="foreach: people">
<tr>
<td><input data-bind="value: FirstName" /></td>
<td><input data-bind="value: LastName"></select></td>
<td><input data-bind="value: Age"></select></td>
<td><select></select></td>
<td>Remove</td>
</tr>
</tbody>
<tfoot>
<tr> <th align=left colspan=4>Total number of people:</th> <th><span data-bind="text: $root.people().length"></span></th> </tr>
</tfoot>
</table>
<button data-bind="click: addPerson, enable: people().length < 5">Add another person</button>
<script type="text/javascript">
function ViewModel() {
var self = this;
self.people = ko.observableArray(ko.mapping.fromJS(#Html.Raw(new JavaScriptSerializer().Serialize(Model))));
self.addPerson = function() {
self.people.push(#Html.Raw(new JavaScriptSerializer().Serialize(new Person() { FirstName = "I am", LastName = "a new Person", Age = "0" })));
}
self.removePerson = function(person)
{
self.people.remove(person)
}
}
ko.applyBindings(new ViewModel());
</script>
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Age { get; set; }
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
My questions is why does people().length return 0?
(Why can't I remove an item from the array using my function removePerson?) ->solved
EDIT:
Here's the generated HTML
Home Page
<script src="/Scripts/knockout.js" type="text/javascript"></script>
<script src="/Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>
My MVC Application</h1>
</div>
<div id="logindisplay">
[ Log On ]
</div>
<div id="menucontainer">
<ul id="menu">
<li>Home</li>
<li>About</li>
</ul>
</div>
</div>
<div id="main">
<table>
<thead><tr>
<th>First Name</th><th>Last Name</th><th>Age</th><th>Department</th> <th></th>
</tr></thead>
<tbody data-bind="foreach: people">
<tr>
<td><input data-bind="value: FirstName" /></td>
<td><input data-bind="value: LastName"></select></td>
<td><input data-bind="value: Age"></select></td>
<td><select></select></td>
<td>Remove</td>
</tr>
</tbody>
<tfoot>
<tr> <th align=left colspan=4>Total number of people:</th> <th><span data-bind="text: $root.people().length"></span></th> </tr>
</tfoot>
</table>
<button data-bind="click: addPerson, enable: people().length < 5">Add another person</button>
<script type="text/javascript">
function ViewModel() {
var self = this;
self.people = ko.observableArray(ko.mapping.fromJS([{"FirstName":"Basti","LastName":"Wuf","Age":"28","FullName":"Basti Wuf"},{"FirstName":"Mawie","LastName":"Mew","Age":"25","FullName":"Mawie Mew"}]));
self.addPerson = function() {
self.people.push({"FirstName":"I am","LastName":"a new Person","Age":"0","FullName":"I am a new Person"});
}
self.removePerson = function(person)
{
//alert(person.FirstName);
self.people.remove(person)
}
}
ko.applyBindings(new ViewModel());
</script>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
ko.mapping.fromJS when given an array turns it into an observableArray.
So, when you do:
self.people = ko.observableArray(ko.mapping.fromJS([{"FirstName":"Basti","LastName":"Wuf","Age":"28","FullName":"Basti Wuf"},{"FirstName":"Mawie","LastName":"Mew","Age":"25","FullName":"Mawie Mew"}]));
self.people will wrapped twice (observableArray contains an observableArray).
So, self.people() would return the inner observableArray. Doing a length on it (a function) will return the number of arguments defined for the function (0 in this case).
Basically, you can just remove the outer ko.observableArray in the view model initialization code and let the mapping plugin do it for you.

Categories