Fill jquery array with server array? - c#

on controller I have MODEL
public partial class CategoryModel
{
...
public int[] SelectedCustomerIds { get; set; }
}
passed to a View from a controller. How can i fill the jquery array by the Model.SelectedCustomerIds
<script type="text/javascript">
var selectedIds = []; << what to replace here

what you can do is u can first create object in jQuery and make a ajax call to server using AJAX and server side you will get tht object and you can simply transfer that object value to your model value!!
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: yourObject, //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (json) {//On Successful service call
var result = json.name;
$("#dvAjax").html(result);
},
error: ServiceFailed // When Service call fails
});
server side
using System.Web.Services;
[WebMethod()]
//[ScriptMethod()]
public static void SendMessage(CategoryModel yourModelObject )
{
}

You can use JSON.NET
<script type="text/javascript">
var selectedIds = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.SelectedCustomerIds))

If you want to use JavaScript side array pushing, then try this
in view put all array elements in hidden
#Html.Hidden("SelectedCustomerIds_"+i, Model.SelectedCustomerIds[i])
and in JavaScript
var selectedCustomerIds = [];
$('*[id*=SelectedCustomerIds_]').each(function () {
selectedCustomerIds.push($(this).val());
});
});

Related

Update List in ViewModel with Ajax ASP .NET MVC

I have a List (List) of Model objects which is presented in a view. I would like to add to that list without refreshing the page - therefore i thought Ajax is a great soloution. Im currently having a hard time getting it working.
My view is rendering a PartialView which contains the list.
Can somebody give me a hint how to pass a list to the controller and then back to the view without updating the whole page?
I hope my question makes sense.
/chris
EDIT:
I've been trying with JQuery. Looks like this:
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/Index", // Controller/View
data: { //Passing data
testString: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
}
}).success(function () {
$("#proever").load("/Video/Index");
});
})
})
With this method i get to HttpPost method in my controller. And i pass the parameters into it succesfully.
[HttpPost]
public ActionResult Index(CommentViewModel viewModel)
{
System.Diagnostics.Debug.WriteLine(viewModel.testString);
System.Diagnostics.Debug.WriteLine(viewModel.videoID);
System.Diagnostics.Debug.WriteLine(viewModel.taskID);
viewModel.testString = "new text string";
return View(viewModel);
}
The problem is now that i can't get the updated viewmodel back to the view.. What am i doing wrong?
In this example I don't update the list but just a test string to see if i can get it updated back to the view..
For those who's interested I solved the problem like this:
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/AddComment", // Controller/View
data: { //Passing data
//Reading text box values using Jquery
sComment: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
}
}).success(function () {
console.log("good");
var txt = document.getElementById('txtArea').value;
console.log(txt);
var taskId = document.getElementById('dropVal').value;
var taskCont = $("#dropVal option:selected").text();
var taskContNum = Number(taskCont) - 1
console.log(taskCont);
var node = document.createTextNode(txt);
var para = document.createElement("div");
para.appendChild(node);
document.getElementById('taskPalace').appendChild(para);
document.getElementById('cola-' + '' + taskContNum).appendChild(para);
document.getElementById('txtArea').value = "";
});
})
})
So if the request succeeds without any errors in the HttpPost method it adds the comment to the database(through the HttpPost) and the jquery adds it to the view.
You need to use persistent data store in your case. Currently, your async post request will change the view model data but data is lost in subsequent http requests when you try to load the view with .load(...) jquery function.
1- Send async request to http post controller action to change the data in db store for example.
2- Read the view model data from db in http get index action. ($("#proever").load("/Video/Index"))
You can try this:
$(document).ready(function () {
$("#btnSave").click(function () {
var model = {
testString: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
};
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/Index", // Controller/View
data: JSON.stringify({ viewModel: model })
async: false,
processData: false,
contentType: false,
dataType: 'json'
}).success(function (json) {
$("#proever").html(json.responseText);
});
})
})

Ajax to MVC controller. Not passing parameters unless Ajax followed by alert

I have the strangest situation. I have two ajax POST. First I had problems passing the parameters to the controller but at some point I got them trough and with some debugging I figured out that I only get all of the values to the controller if my ajax definition is followed by an alert.
One of them:
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Telefon: $('#nr').val(),
IsEnkel: false,
PassId: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
},
Participanter: getParticipant(),
ParticipantMail: getParticipantMail()
},
traditional: true,
success: function (result) {
// window.location.href = '#Url.Action("IntresseAnmälan", "Contact")';
}
});
alert("Hur sparas dina uppgifter?");
Here are my Getters for name and mail. The form-elements(input type mail and text) theese are dynamicly added to the form if the user wants clicks a button two inputs are added. Then theese functions returns an array with the inputed values from the form.
function getParticipant() {
var p = [];
for (var i = 1; i <= participantCount; i++) {
var name = '#anNamn' + i;
p[i -1] = $(name).val()
}
return p;
}
function getParticipantMail() {
var p = [];
for (var i = 1; i <= participantCount; i++) {
p[i -1] = $('#anMail' + i).val();
}
return p;
}
And here is my controller. I've removed the body in the controller. It saves to the Db and send a verification mail to the admin.
[HttpPost]
public ActionResult IntresseAnmälan(BokningContainer bokning)
{
//Saves to Db and Send a verification mail to admin
}
If I exclude the alert after the ajax some parameters are passed, I think it's Namn and Mail, but most of them not passed. I'm quite puzzled.
Also, is ajax the only way to pass an object to a controller from jQuery?
Also, is ajax the only way to pass an object to a controller from
jQuery?
No, you can use a regular HTML Form to submit your data, you just have to conform to the expected object in the controller Action (should be decorated with HttpPostAttribute) - There is a Model-Binding process which attempting to bind the Request data to your domain object.
You don't need to pass every field's value using jQuery. Instead you can create a form whose data you want to post like :
<form id="frmTest">
... add input types here
</form>
and you can pass data of form using $('#frmTest').serialize() method to the controller
$.ajax({
type: "POST",
data: $('#frmTest').serialize(),
url: "url",
dataType: "json",
success: function (data) { alert('worked!'); },
error: function (data) {
alert('error');
}
});

JQuery getJSON in MVC

I have the following JSon call that I want to call a method in Controller & accepts JSon object to update Partial View:
<script type="text/javascript">
function DoAjaxUpdate(btnClicked) {
btnClicked = $(btnClicked);
var $form = btnClicked.parents('form');
var url = '#Url.Action("Remove")';
$.getJSON(
url,
$form.serialize(),
function () {
if (data.htmlPartialView != null) {
return $("#divPartialView").load(obj.htmlPartialView);
}
});
return false;
}
</script>
Unfortunately, this isn't passing the data properly and instead appends it to the URL as a query string such as: http://www.myLink.com/MyController/Remove?dataID=1359&dataMember=1
Please help. Thanks
That's what happens with $("form").serialize(). It will serialize everything on the form and put it on the query string.
As long as your Remove action method takes an instance of the model that is on your original view, then it will be transformed using the values in the query string.
To send it as JSON, you'd have to use JSON.stringify():
JSON.stringify($form.serialize())
The callback need parameter,like this:
$.getJSON(
url,
$form.serialize(),
function (obj) {
if (obj.htmlPartialView) {
$("#divPartialView").load(obj.htmlPartialView);
}
});
by the way,if (obj.htmlPartialView) is same to if (data.htmlPartialView != null)
You are calling getJSON which sends the data as a GET request which uses the querystring. If you want to use the POST method, use (from the jQuery site):
$.post(url, data, function(data) {
});
or
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
More information: http://api.jquery.com/jQuery.post/

Getting value from a dropdown list that was populated with AJAX

I had populated an ASP.net dropdown list with AJAX now I need to get the Id to store in into the database in a C# method, (I'm using LINQ)
This is my webmethod
[WebMethod]
public static ArrayList GetLanguageList()
{
ArrayList lstArrLanguage = new ArrayList();
IQueryable<Common.Town> myList = new SupplierBL().GetTowns();
foreach(Common.Town t in myList)
{
string name = t.Name;
string id = t.TownId.ToString();
lstArrLanguage.Add(new ListItem(name, id));
}
return lstArrLanguage;
}
My test.aspx code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "test.aspx/GetLanguageList",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#ddlLanguage").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function () {
$('#<%=ddlLanguage.ClientID%>').append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("An error has occurred during processing your request.");
}
});
});
</script>
You can't get selected value from DropDownList if you adding options in javaScript. You can try the following
string selectedValue = Request.Form[ddlLanguage.UniqueID];
This question may be useful also.
If you populate the value of dropdown via ajax than it can't be available on Server Side because the page doesn't postback during ajax request.
In order to get the value of dropdown in C# use below snippets :
String _value = Convert.ToString(Request[ddlLanguage.ClientID]);
Hope this will help !!

Passing Array to Action from a $.post

I am having trouble passing my array via a $.post.
The Javascript
var privIDs = [1,2,4,5];
$.post("/Home/GrantPrivilegesToUser", { privilegeIDs: privIDs }, function (data) {
alert("Data Loaded: " + data.success);
});
The Action
public ActionResult GrantPrivilegesToUser(int[] privilegeIDs)
{
return Json(new {success=true});
}
The action sees privilegeIDs as null. Any ideas?
You need to set jQuery.ajaxSettings.traditional = true; for you jQuery ajax setting. In jQuery 1.4 they changed the way items are serialized in a form post.
please see:
http://forum.jquery.com/topic/nested-param-serialization
And:
How can I post an array of string to ASP.NET MVC Controller without a form?
I use JSON to pass data as a string using the JSON2 library: http://www.json.org/js.html
var privIDs = [1,2,3,4,5];
var data = JSON.stringify({privilegeIDs : privIDs});
$.POST("/Home/GrantPrivilegesToUser", data, function (data) {
alert("Data Loaded: " + data.success);
});
And the action would use the WebMethod type:
[WebMethod]
public object Entry_GetFormOptions(string privilegeIDs)
{
return new {success=true};
}
There are both built-in and 3rd party functions for parsing the received JSON to access the privilege IDs.
Let me know if this does or does not help.
This is what I ended up doing. Might be helpful to someone...
var privIDs = [1,2,4,5];
$.ajax({
type: "POST",
url: "/Home/UpdatePrivileges",
data: { privilegeIDs: privIDs },
traditional: true,
success: function (json) {
alert(json.success);
}
});
If you use .ajax instead of .post you can include traditional: true

Categories

Resources