how send table content to controller - javascript

I have a problem to send table global from view to controller the table in controller is full but in controller affect a null for the composant of table
and this is the controller method :
public Boolean ajoutermodule(string nom, modules[] global, int cv)
{
return true;
}
And this the view and method ajax how i append my table global and how i sent this table global from view to controller :
function Addmodule() {
var nom = $("#nomprojet_I").val();
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"global": global,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
var global = [];
function OnGetSelectedFieldValues(s, e) {
var SelectedUsers = $("#teamlist_I").val() + " " + $("#teamid_I").val();
listbox.AddItem(SelectedUsers);
var nom = $("#teamlist_I").val();
var id = $("#teamid_I").val();
global.push({ "id": id, "nom": nom });
debugger;
}
and when i added the length it send him correctly to controller.

but method ion your controller like this:
public Boolean ajoutermodule(string nom, stirng s, int cv)
{
return true;
}
and add this to your method ajax
var s = JSON.stringify(global);
function Addmodule() {
var nom = $("#nomprojet_I").val();
var s = JSON.stringify(global);
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"s": s,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
it will work inchallah

Please try this code for ASP.NET MVC –
View.cshtml
<table id="StepsTable">
<tr>
<td>Step 1</td>
<td>#Html.TextBox("step1")</td>
</tr>
<tr>
<td>Step 2</td>
<td>#Html.TextBox("step2")</td>
</tr>
<tr>
<td>Step 3</td>
<td>#Html.TextBox("step3")</td>
</tr>
</table>
<input id="SendToControllerButton" type="button" value="Send to the server"/>
<script>
$(document).ready(function () {
$("#SendToControllerButton").click(function () {
var data = {};
//Collects the data from textboxes and adds it to the dictionary
$("#StepsTable tr").each(function (index, item) {
var tds = $(this).find("td");
var textBoxTitle = $(tds).eq(0).text();
var textboxValue = $(tds).eq(1).find("input").val();
data["stepsDictionary[" + index + "].Key"] = textBoxTitle;
data["stepsDictionary[" + index + "].Value"] = textboxValue;
});
//Makes ajax call to controller
$.ajax({
type: "POST",
data: data,
url: "/Home/ProcessStepsValues",
success: function (message) {
alert(message);
}
});
});
});
</script>
And then sends the data to controller
Controller.cs
[HttpPost]
public string ProcessStepsValues(Dictionary<string, string> stepsDictionary)
{
string resultMessage = string.Empty;
if (stepsDictionary != null)
{
resultMessage = "Dictionary data passes to controller successfully!";
}
else
{
resultMessage = "Something goes wrong, dictionary is NULL!";
}
return resultMessage;
}
Please refer the site for more details
https://alexkuznetsov.wordpress.com/2013/05/08/asp-net-mvc-pass-dictionary-data-from-view-to-controller/

Related

ASP.NET MVC ADO.NET Query per table row

Here I have this table:
If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=#id" per row.
One of the main purpose of this is when i filter the table, only the visible rows will be passed.
I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.
JS:
var HTMLtbl =
{
getData: function (table) {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
//I don't know what to do here now, please help
}
My Solution based on Mostafa's answer:
JS:
var HTMLtbl =
{
getData: function () {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("#btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
string result = string.Empty;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
con.Open();
foreach (var arr in array)
{
SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", arr[0]);
cmd.ExecuteNonQuery();
}
con.Close();
}
catch (Exception ex)
{
result = ex.Message;
}
return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
}
I can now use this for more complicated stuff, thanks
If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,
<input type="button" data-rowId="1" class="changeActivationState">activate</input>
in this example I added a data field to my imput after that I define this javascript method:
$(".changeActivationState").click(function(){
$(this).data("rowId")//get the selected row id and call you service
});
using this code you can read first element for each row and perform a web service call for all rows
var arr = [];
$("#yourtable tr").each(function(){
arr.push($(this).find("td:first").text()); //put elements into array
});
and using this code you can read all rows into a json object
var tbl = $('#yourtable tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
assume that you passed the list to action
int[] passedIDsfromBrowser = ///filled with data that comes from browser;
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
this is a pseudo code.
or if you want a loop and updating each row with a loop
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
connection.Open();
for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
command.CommandText = "YOURQUERY";
command.ExecuteNonQuery();
}
connection.Close();

Unable to retrieve data from html

As for my below code i am not able to get sectionID from tr, i need to get dynamic id of sectionID on each delete button click but it is always giving me null
Here is the Jquery Script :
<script>
$(function () {
$('.btnDelete').click(function () {
var sectionID = $(this).closest('tr').find('.sectionID');
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'CheckSectionIDagainststudentID',
data: JSON.stringify({ sectionID: sectionID.html() }),
success: function (data) {
if (data == true) {
$.alert("Cannot delete | Students exsisting in this
Section!");
}
else if (data == false) {
var secCode = JSON.parse(this.data);
var code = sectionid['sectionid'];
window.location.href = "SectionDelete?Page=data&sectionid="
+ code;
}
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
and here is Razor Page
#foreach (var item in Model)
{
<tr class="sectionID">
<td >
#Html.DisplayFor(modelItem => item.sectionID)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td class="secCode">
<button style="width:49.5%" ID="Button2" type="button" onclick="location.href='#Url.Action("SectionEdit", "Section",new { id = item.sectionID, name = item.name })'">Edit</button>
<button style="width:49.5%" ID="deletebtn" runat="server" type="button" onclick="location.href='#Url.Action("SectionDelete", "Section",new { id = item.sectionID, name = item.name })'">Delete</button>
<button class="btnDelete">Delete</button>
</td>
</tr>
}
This is Controller Which i need to pass data to
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string sectionID)
{
return Json(sectionID);
}
As per your question you are not able to get value from var sectionID = $(this).closest('tr').find('.sectionID');
therefore here is a way you can achieve your result
//Your Dynamic Button should look like this
//in value Bind your sectionID # MVC
<button class="btnDelete" value="5" onclick="AjaxDelete(this)">Delete</button>
//For Function
function AjaxDelete(values) {
//Write this in Ajax
//Fetch Value from attribute value
var sectionID = $(values).attr("value"); // you will get 5 as value
//Your Ajax Call with SectionId as Parameter
}
Edit :
as you have got value
U can split the value by below code
where string is your var of sectionID
if ((~string.indexOf('\n '))) {
string= string.split('\n ')[1].split('\n')[0];
}
Use string array :
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string[] sectionID)
{
return Json(sectionID);
}

In MVC 4 my textarea is not resetting from default value

I've created a MVC project with Browse button and upload button. When the user clicks on Browse and select a file and click upload, the file contents has to be displayed in a Textarea. By default when I load the page, I'm displaying default text in textarea. Once the user uploads a file, I'm trying to display the contents in that textarea.
Problem is while I'm trying to reset the content, the textarea is not getting reset. Any help is really appreciated.
View:-
#model DigitalUnderwritingFacade.Models.DigitalUnderwritingModel
<h2>DigitalUnderwriting</h2>
<div>
#using (Html.BeginForm())
{
<table style="vertical-align:middle">
<tr>
<td>Upload a json file : <input type="file" id="btnbrowse" name="browse" value="Browse"></td>
</tr>
<tr>
<td><input type="button" id="btnfileUpload" name="btnfileUpload" value="Upload" /></td>
<td><div id="validateSelectedFile" class="warrningMessage">Please browse a valid json file</div></td>
</tr>
<tr>
<td>#Html.TextAreaFor(model => model.JsonText, new { #class = "form-control", cols = "120", rows = "45", #id = "textarea" })</td>
</tr>
<tr>
<td><input type="submit" id="Savebtn" value="Save"></td>
</tr>
</table>
}
</div>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$("#btnfileUpload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("btnbrowse").files.length;
var browsedFile = document.getElementById("btnbrowse").files[0];
var fileextension = browsedFile.name.split('.').pop();
if (totalFiles == 0)
$("#validateSelectedFile").show()
if ((totalFiles != 0)) {
if (fileextension == 'json') {
formData.append("FileUpload", browsedFile);
$.ajax({
type: "POST",
url: '/DigitalUnderwriting/Upload',
data: formData,
contentType: false,
processData: false,
success: function (result) { }
});
}
else {
alert("Please select a valid json file.");
}
}
});
</script>
Controller:-
DigitalUnderwritingModel model = new DigitalUnderwritingModel();
private string InputJsonPath = System.Configuration.ConfigurationManager.AppSettings["DefaultJson"].ToString();
private string ResponseJsonPath = System.Configuration.ConfigurationManager.AppSettings["JsonResponsesPath"].ToString();
//
// GET: /DigitalUnderwriting/
public ActionResult Index()
{
StreamReader reader = new StreamReader(InputJsonPath);
if (TempData["ResponseJson"] == null)
{
model.JsonText = reader.ReadToEnd();
}
else
{
model.JsonText = TempData["ResponseJson"].ToString();
TempData["ResponseJson"] = null;
}
return View(model);
}
[HttpPost]
public ActionResult Upload()
{
ModelState.Remove("JsonText");
var streamfile = new StreamReader(Request.Files[0].InputStream);
var streamline = string.Empty;
while((streamline = streamfile.ReadLine()) != null)
{
model.JsonText += streamline;
}
TempData["ResponseJson"] = model.JsonText;
return RedirectToAction("Index");
}
Model:-
[DataType(DataType.MultilineText)]
public string JsonText { get; set; }
Try this, my friend. I think you dont need set id for Textarea.
$("#btnfileUpload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("btnbrowse").files.length;
var browsedFile = document.getElementById("btnbrowse").files[0];
var fileextension = browsedFile.name.split('.').pop();
if (totalFiles == 0)
$("#validateSelectedFile").show()
else{
$('#JsonText').html(browsedFile.name); //set name file
if (fileextension == 'json') {
formData.append("FileUpload", browsedFile);
$.ajax({
type: "POST",
url: '/DigitalUnderwriting/Upload',
data: formData,
contentType: false,
processData: false,
success: function (result) { }
});
}
else {
alert("Please select a valid json file.");
}
}
});
[HttpPost]
public ActionResult Upload()
{
TempData["ResponseJson"] = model.JsonText;
ModelState.Remove("JsonText");
var streamfile = new StreamReader(Request.Files[0].InputStream);
var streamline = string.Empty;
while((streamline = streamfile.ReadLine()) != null)
{
model.JsonText += streamline;
}
return RedirectToAction("Index");
}

A script for upadate textbox's value in asp.net mvc didn' work

I want to update textbox's value(that contains cookie's value) using Ajax in asp.net MVC5 . I'm very new in JavaScript and I wrote these codes , but my code didn't work . I didn't get any error but it's not working. I wrote JavaScript in foreign file 'UpdateTxtBox.js' and I added <script src="~/Scripts/UpdateTxtBox.js"></script> to Layout .
Could anyone tell me what's the problem ?
$(function () {
$("textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
a part of Basket.cshtml
#using (Html.BeginForm("AddToCart", "Goods", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(modelItem => item.Count, new { #class="text textCountProduct" , style="width:40px;" , productid=item.GoodDetails.DetailsGoodID})
}
Good controller
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
//Script = "alert('Good added successfully');",
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
Update post :
I added [HttpPost] to controller action result and add some alert to javascript
$(function () {
alert("aleeeert");
$(".textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
alert(count);
alert(id);
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
it's working fine but when I refresh page , data didn't saved
Since you have specified textCountProduct as CSS class, you need to prefix it with . to use Class Selector (“.class”), As of now its looking for Element textCountProduct which obviously doesn't exists.
Use
$(".textCountProduct").change(
You have made mistake here $("textCountProduct") use . as selector.
It should be $(".textCountProduct")
and
Check path of your script included
<script src="~/Scripts/UpdateTxtBox.js"></script>

HTML table not updating, after pushing new item to knockout observableArray

I am having trouble updating my HTML UI.
When the document load and calls "getAllProducts()", the HTML UI displays all my items and with the right css class for 'styleStatusCss', and the right 'displayName', the problem is that when I try to update my observableArray with a newly updated product (product name or status has changed), the html UI does not update and remains the same
So here is a quick list of what is happening:
getUpdatedProducts() is called every 25 sec, and returns, any product
that has been updated
I check how many products my observable array has: appVM.itemList.length and it does have 100 (as expected!), I also check that the json product that has been sent back has some modified data, and indeed it has changed!
I then create the javascrip obj MyProduct using that product json object
Now I add my newly created javascript obj MyProduct to the observablearray: appVM.itemList.push(newUpdatedProduct);
And finally I check how many items my observablearray has, after doing the push, (and since I cannot see any changes on the HTML UI), and appVM.itemList.length now says 101 !!! How can that be? the HTML UI still displays the data as it was after the initial load
Please see below most of the code
HTML
<table >
<tbody data-bind="foreach: itemList">
<tr>
<td>
<div data-bind="css: styleStatusCss"></div>
</td>
<td>
<div data-bind="text: displayName"></div>
</td>
</tr>
</tbody></table>
And here is the javascript:
<script type="text/javascript">
var appVM;
var initializeItems = false;
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$(document).ready(function () {
getAllProducts();
});
setInterval(function () {
if (initializeItems) {
getUpdatedProducts();
}
}, 25000);
function getAllProducts() {
var url = '#Url.Action("_AllProducts", "Home")';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
})
.success(function (result) {
initializeItems = true;
appVM = new AppViewModel();
var mappedProducts = ko.utils.arrayMap(result.ItemList, function (item) {
var con = new MyProduct(item);
return con;
});
appVM.itemList = mappedProducts;
ko.applyBindings(appVM);
})
.error(function (xhr, status, error) {
alert("FATAL ERROR");
})
}
function getUpdatedProducts() {
var url = '#Url.Action("_UpdateProducts", "Home")';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
})
.success(function (result) {
if (result.HasNewData) {
alert("we have some data");
alert("START COUNT: " + appVM.itemList.length); //this shows all my 100 products -> START COUNT: 100
alert("Number of new items: " + result.ItemList.length); // i only get one product back for easy debugging
for (index = 0; index < result.ItemList.length; ++index) {
var updatedProdJson = result.ItemList[index]; //get the json for the product
alert("New prod json: " + objToString(updatedProdJson)); //just for debugging print out in a readable format
var newUpdatedProduct = new MyProduct(updatedProdJson);//create our MyProduct object (which has all properties as observable)
appVM.itemList.push(newUpdatedProduct); //add our new MyProduct to the list
alert("FINAL COUNT: " + appVM.itemList.length); // --> FINAL COUNT: 101
}
}
})
.error(function (xhr, status, error) {
alert("Error: " + status);
})
}
function AppViewModel() {
var self = this; //so it references the viewModel object
self.itemList = ko.observableArray([]);
self.doAlert = function () {
alert("HERE");
}
}
function MyProduct(data) {
//alert("DATA: " + objToString(data));
this.Id = ko.observable( data.Id);
this.Name = ko.observable(data.Name);
this.status = ko.observable(data.Status);
this.displayName = ko.computed(function () {
var fullnmae = this.Id() + " " + this.Name();
return fullnmae;
}, this);
this.styleStatusCss = ko.computed(function () {
var pStatus = 'divstatusnone';
if (this.status() === 'H')
pStatus = 'divlowstatus';
if (this.status() === 'D')
pStatus = 'divhighstatus';
return pStatus;
},this);
}
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
Hope somebody can tell me where i went wrong.
Many thanks,
in getAllProducts, you're assigning the results to itemList, losing your observable array:
appVM.itemList = mappedProducts;
you need to do this instead:
appVM.itemList(mappedProducts);

Categories

Resources