MVC :: Passing List To Action
Sep 8, 2010[Code]....
Somebody will come to my page, RenderMyThing.aspx ... and I always want to pass a list of strings
[Code]....
[Code]....
Somebody will come to my page, RenderMyThing.aspx ... and I always want to pass a list of strings
[Code]....
I am rather new to ASP.NET MVC and am trying to develop good practices and have studied a few tutorials and videos. There seems to be some differences in how people define the signature of a typical edit action method - sometimes the id (primary key) is listed and sometimes not. It seems like letting the framework do the model binding is a GOOD THING, so I will probably have the model (or view model) as a parameter:
ActionResult Edit(int id,
CompanyViewModel company);
ActionResult Edit(CompanyViewModel company);
But, should the id be a parameter too? I assume it is common-place to have the id in a hidden form field as well so the id (primary key) is then already bound in the model (or view model) - if so, what is the id parameter good for? Or should it be the other way around - keep the id parameter and do not bother using a hidden field for it? What are the pros and cons and what is the best practice?
I have an action link that I use to pass values to a controller using this statement:
<%: Html.ActionLink("Addition 1 to 10", "CreatePdf", "Pdf", new { id = 32, stOperation = "Add", stNumbers = "10" }, null)%>
So when a user clicks on the above link the controller CreatePDF is called with the parameters of id, stOperation, and stNumbers. I then use these three parameters to return a pdf document to the user.I also have a checkbox on the html page as defined by:
<%: Html.CheckBox("chkAnswers", false) %>
My question is how to pass the value of this checkbox in the above HTML.ActionLink? I have a tutorial on using the submit button to submit an entire form and the associated data. However I do not want the user to have to click a button. Instead I'd like return the value of the checkbox in the action link but I'm not sure how to do this. I want something like:
%: Html.ActionLink("Addition 1 to 10", "CreatePdf", "Pdf", new { id = 32, stOperation = "Add", stNumbers = "10", checkboxValue = true or false }, null)%>
public ActionResult RenderMyThing(IList<String> strings)
{
return View("RenderMyView");
}
How do I pass in strings?
routes.MapRoute("MyRoute", "RenderMyThing.aspx", new { controller = "My", action = "RenderMyThing" });
Is there a way I could pass in strings here?
Secondly, how does ASP.NET MVC know that action is my action, and controller is my controller. Like I saw this in samples, and it does work, but isn't it just an anonymous object with no type?
I'm sure something like this worked before for taking a type and pass it to another action method (I cannot / never use TempData)
[Code
I have the following javascript. Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null? I checked the javascript and the variable "cnt" is 1 not 2. Why would that be?
[code]
$("#Save").click(function () {
var title = $("#recipetitle").val();
var category = $("#category").val();
var preptime = $("#prepTime").val();
var preptimeperiod = $("#lstPrepTime").val();
var cooktime = $("#cookTime").val();
var cooktimeperiod = $("#lstCookTime").val();
var rating = $("#rating").val();
var method = $("#method").val();
var jsontext = '{ "RecipeTitle": "' + title + '",';
jsontext += '"CategoryID":' + category + ',';
jsontext += '"PrepTime":' + preptime + ',';
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",';
jsontext += '"CookTime":' + cooktime + ',';
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",';
jsontext += '"Rating":' + rating + ',';
jsontext += '"Method":"' + method + '",';....................
In one view (view1) there is a text box and a button beside it. i click on that button, i am popping another view (Create view) as a seperate window. in create view i am entering some values and creating a record in db. out of these values one value i have to send back to "View1". how can i send this value? i am opening view2 from view1 like
<input type="button" value="Get ID"
onclick="window.open('<%=Url.Action("Create","Controller1") %>',
'','scrollbars=yes,width=800,height=800,resizable=yes');"
/>
View2 contains some fields like Name,Email etc... and I click "Create" to call HTTPPOST. there i add the values to db including a generated guid. i want to send this ID to view1.
Basically, I have an HTML Form and would want to pass the data from the form to n asp.net mvc controller, then the controller would return an XML for client side manipulation.
Here is my initial code:
[Code]....
When I run and debug, I get a message that says "attr(..) is null or not an object. I am still trying to learn web development using ASP.NET MVC.
I have 2 classes that are used to mirror the data from an ajax call. One (Customer) contains a property which is name, and the other is an array of Products.
Public Class Customer
Private _Name as String
Private _Products as Product()
Public Property Name() As String
[Code].....
I am trying to send json data from view to controller action. But the issue is the data is not populating in the action parameter List<Score>.
View Model:
public class Score
{
public int QuestionId { get; set; }
public int PrevAnswerId { get; set; }
public int CurrAnswerId { get; set; }
public string CurrAnswerName { get; set; }
}
Json Data look like:
[
{QuestionId:1, PrevAnswerId:3, CurrAnswerId:3, CurrAnswerName:'Known to Broker'},
{QuestionId:2, PrevAnswerId:7, CurrAnswerId:7, CurrAnswerName:'Completed'},
{QuestionId:3, PrevAnswerId:10, CurrAnswerId:10, CurrAnswerName:'Report'}
]
On window load, I will construct the Json object using "eval()" function and do some operation in the data before its save. On Save Click, I will call the action through the ajax call.
$.ajax({
url: url,
type: "GET",
dataType: 'json',
data: {score: ScoreJson},
contentType: "application/json; charset=utf-8",
success: function () {
alert("succes");
},
error: function () {
alert("error...");
} });
Action:
public ActionResult SaveScore(List<Score> score)
{
// do something...
}
But here score comming as collection of 3 elements with zero(for interger property)/null(for string property) values. When I checked in the request I found the data in "parama" property like.
"Score%5b0%5d%5bQuestionId%5d=1 &Score%5b0%5d%5bPrevAnswerId%5d=3 &Score%5b0%5d%5bCurrAnswerId%5d=3 &Score%5b0%5d%5bCurrAnswerName%5d=Known+to+broker&
Score%5b1%5d%5bQuestionId%5d=2 &Score%5b1%5d%5bPrevAnswerId%5d=7 &Score%5b1%5d%5bCurrAnswerId%5d=7 &Score%5b1%5d%5bCurrAnswerName%5d=Completed&
Score%5b2%5d%5bQuestionId%5d=3 &Score%5b2%5d%5bPrevAnswerId%5d=10 &Score%5b2%5d%5bCurrAnswerId%5d=10 &Score%5b2%5d%5bCurrAnswerName%5d=Travelers+Report&".
But I am not sure why it is not getting populated in the score list. One full day I spent for this issue but till now I didnt find the solution for this issue.
I have an ASP.NET MVC controller action with the following VB.NET signature:
<HttpPost()>
Public Function ClosestCities
(ByVal position As MapCoordinate, ByVal citiesCount As UInteger) As JsonResult
The MapCordinate class is:
Public Class MapCoordinate
Public Latitude As Double
Public Longitude As Double
End Class
If I'm trying to send an Ajax POST in jQuery to the ClosestCities action, what should my request look like?
When I use the following code to POST to this action, in the debugger window of VS, position.longitiude and position.latitude are equal to 0.0 (0D):
[code]....
I have an action where I get the list from the database and pass it to the view. Now, I want that when I fire another action I can somehow get hold of that list (List). How can I do that since ViewData and the TempData is erased on each request.
View 1 RepliesIn Short: Does any know a way from the base controller to get a list of actionFilters being applied to the current executing action?
The Long:I am using ASP.NET MVC 1.0 framework. I have a "RequireSSL" actionFilter that I've recreated for checking out, however, if someone leaves the checkout and goes back to the store I would like to forward them back to non-secure version of the site.It would be helpful in the base controller (I am using a custom base controller that inherits from the default Controller) to find out what actionFilters are being applied to the current action.I could include this into the global.asax.cs
I got a list of checkboxes on my form, and a jquery script that catch a button click to get all the selected items (in an array) and post to a controller action.
This is my script: (yes A, looked at your sample but cannot get this to work)
[Code]....
That alert will print out correctly (like 1,3,5).
However when the above post hit my controller action, "selectedInvestments" are null, which I can't figure out why (back to my tekpub jquery videos, can't go on like this)
[Code]....
I am using HTML.BeginForm to create a form on my page. I need to pass a list of classes I created as a parameter. It's done like this:
<%
using ( Html.BeginForm("DisplayCompanions", "CCDReviewController", new { CompanionList = Model.CompanionList} ) )
{ %>
When I click a "Continue" button (enclosed in the form tag), the "DisplayCompanions" method on my Controller ("CCDReviewController") should be called, as I've set a breakpoint on it. But it's not being called.
Note that Model.CompanionList is a generic list of classes that I created.
I am using VS 2010, C# and Sql Server 2008.From the database, i am returing a list, which contains around 25 columns. am binding the list to the grid. After the list is binded, i am trying to create a dataset from the list. But I would like to have only 5 columns in the dataset, out of the 25 columns returned from the list. How to achieve this?This is the code I have used now:
[Code]....
I want to pass columns like, schoolid, schoolname,courseoffered,Ranking,Dateofopening from the list to the dataset .How to pass the columns from the list to create the Dataset
I've a situation where I want to pass list of records via Ajax/JQuery.
public JsonResult GetListOfRecords()
{
return Json(_repository.GetAllRecords());
}
when I call this action method with jQuery, it doesn't work:
$.getJSON('GetAllRecords', function(data){ // data is IQueryable<T> or IEnumerabel<T>
$.each(data, function(d) {
$('#somewhere').html(d.Title); //d is SomeModelType and Title is property of that type
});
[Code]....
it just displays title...
My Question is that "I want to pass IQueryable or IEnumerable through ajax."
ss a list of objects as a paramter in an actionlinkAt the moment when I try to do this the list is always empty by the time it reaches the controller!
<%= Url.Action("ActionName", new { list = Model.ListOfObjects}) %>
public ActionResult ActionName(List<Object> list)
{
//Do stuff
}
how to get text value of dropdown list box by its index.
i want to read the ddlproject.selectedindex = 0's text and assign it to a variable strProject.
I have a GridView which I have a List bound to - I want to be able to allow filter of the data based on multiple CheckBoxLists. For arguments sake let's say I have a List of Jobs, and I want to filter the jobs by code - So I would have a CheckBoxList likeC#ASP.NETphpF#etc..If someone selects multiple codes, how do you pass the values into a List to rebind to the GridView? Is there a way to pass values as an array? Or maybe a comma seperated string?Any examples (I'm a C# boy) would be greatly appreciated, and I hope I have explained it properly :S
View 3 RepliesI have a name/value pair in a List<T> and needing to find the best way to pass these to a stored procedure.
Id Name
1 abc
2 bbc
3 cnn
What is the best way to accomplish this?
I have an ASP.NET PageMethod with the following signature:
<WebMethod()> _ Public Shared Function SaveCodes(ByVal codes As List(Of Code)) As String
I am trying to pass a JSON object to the PageMethod from the client side, but I get an error that the type String cannot be converted to type of List<Code>.
Here is the json that I'm building on the client and sending to the method:
[code]....
I have been able to pass in simple data types and a single instance of the Code class, but I can't seem to find the magin to pass a List to the server method. Can anyone show me what I'm doing wrong?
I need to pass a list of Entity Objects from Controller to View but not put it in the Model context. It is the users homepage, but I am putting a list of alerts on the users home page(somewhat like facebook). So I need the User Context as the Model I pass but need to pass the Alert model as well so I can show the list of alerts.. How would I do that? The code below is what I have so far..
UserController
[Code]....
UserRepository
[Code]....
I have googled a lot to find any solution to pass the selected dropdownlist item to another page.
In my controller view, I have a got list of of items:
List<SelectListItem> PackagingService = new List<SelectListItem>();
We need to create a simple web service in ASP.NET that can be called from PHP or other languages. This in turn will be used to update records in a database for an item submission.
The core part is fairly simple, we have a base set of fields for the object - first name, last name, birth date, city, etc. In addition however we need to accept a list of items associated with that object that can range from 0-n.
Jan 1 2009, ABC
May 1 2010, 123
Jun 30 2010, XXXXX
What would be the best way to structure this so it can be easily passed to the ASP.NET web service and processed as a single call for the entire object? Would passing the list of items as a single delimted string be a wise approach? Ex: Jan 1 2009, ABC|May 1 2010, 123|Jun 30 2010, XXXXX