How to pass JSON to controller action? - asp.net

I have some textboxes and a table of data created client side that I want pass to a controller as JSON.
Can you please give me the syntax for this?
I want to use Jquery to enumerate the table.
Assume I have 2 textboxes called name and age.
Assume a table with 2 columns. one column with class
called phonetype and one column class called phonenumber.
So how do construct the JSON from this?
Thanks in advance.
Malcolm

Sending Json to a ActionResult with an object as the parameter and using the JsonValueProviderFactory do the deserialization.
Sending JSON to an ASP.NET MVC Action Method Argument
Looping through table rows:
var tableRows = $('.TableDemo tr');
tableRows.each(function () {
var tdText = $(this).find('#id_of_td_with_data').text();
});

Related

Passed a List thru ViewBag but can't do LINQ Select on it from MVC Controller

I am trying to pass a 2nd List of objects from the Controller to the
View via the ViewBag
Here is the line from my controller code.
ViewBag.FeaturedProductList = await Service.SendAsync(new ProductQuery());
The return object is the following
public class FeaturedProductListDto : IDto
{
public IEnumerable<FeaturedProductDto> Contents { get; set; }
}
In the View, I need to do a linq to select from the
ViewBag.ViewBag.FeaturedProductList in the following line.
#foreach (var productGroup in ViewBag.FeaturedProductList.Select((e,
i) => new {Product = e, Grouping = (i/3)}).GroupBy(e => e.Grouping))
{
}
I need to group the number of items from the list in sets of 3 but the
Select is throwing an error as the following
Cannot use a lambda expression as an argument to a dynamically
dispatched operation without first casting it to a delegate or
expression tree type.
I used the same code for my other List which I passed in as the Model
and it works.
This line works. #foreach (var productGroup in Model.Select((e, i) =>
new { Product = e, Grouping = (i / 4) }).GroupBy(e => e.Grouping))
Do I need to recast the ViewBag.FeaturedProductList? What is the fix
for this? Any help is greatly appreciated. Thanks.
ViewBag is a dynamic dictionary. Items in this dictionary are of type dynamic. You cannot use LINQ methods on that.
You need to cast ViewBag.FeaturedProductList to FeaturedProductListDto type and use the Contents property which is a collection type on which we can apply LINQ extension methods.
#foreach (var item in ((FeaturedProductListDto) ViewBag.FeaturedProductList).Contents
.Select(//your existing select code goes here))
{
}
I am not quite sure what you are trying to do with the GroupBy inside your Select. My personal preference is doing all such things in the action method/another layer which provides data to the action method and keep the razor markup with minimal C# code, and with more HTML markup for the page. :)

How can I access the data inside dynamically created table rows on the server side?

Just a little background: I am creating an ASP.NET MVC web application.
In my main page I created several table rows using AngularJS, and while I can access them on the client side, my ultimate goal is to process the data on the server side using vb.net. A nudge in the right direction would be greatly appreciated. Thank you.
Here is my AngularJS controller used to dynamically add rows to my html table.
function TableController($scope){
$scope.requests = [];
$scope.addCertificate = function () {
var certificate = {
emailAddress: $scope.emailAddress,
certificateType: $scope.certificateType,
searchType: $scope.searchType,
submittedNumbers: $scope.submittedNumbers,
};
$scope.requests.push(certificate);
};
$scope.removeCertificate = function (index) {
$scope.requests.splice(index, 1);
};
}
Make sure the input fields, select boxes, textareas, etc. in the dynamic tables have names associated with them.
You then have two options:
Use the same name for the input in each row. For example, if you have a table with five rows, and each row has an input to hold last name, then those five inputs would be named "LastName". You're post function could then have the parameter LastName, which would be a comma-delimited string of your values:
[HttpPost]
public ActionResult YourPostFunction(string LastName)
{
// split LastName on "," to convert to an array or List and then process.
}
Index the name of the inputs like you would an array. For example, if you have a table with five rows, and each row has an input to hold last name, then those five inputs would be named LastName[0], LastName[1], LastName[2], LastName[3], and LastName[4]. You should then be able to access those fields via a MVC action like this:
[HttpPost]
public ActionResult YourPostFunction(List<string> LastName)
{
}
In either case, your MVC action would not need to know the number of LastName fields that were posted to you. You would have a comma-delimited string or a List you could then iterate through and process accordingly.
More details (and code, if possible) would be needed to provided a more detailed answer.

how to pass multiple key/value pairs in a single variable using query string?

I have one requirement like passing multiple values in the query string in a single variable.
Id=(refine_1=cgid=womens&refine_2=c_refinementColor=Black&refine_3=price=(0..500))
Is it possible to accept value like above sample from the query string?if yes,please tel me how to achieve this?
You should URL encode it:
?id=(refine_1%3Dcgid%3Dwomens%26refine_2%3Dc_refinementColor%3DBlack%26refine_3%3Dprice%3D(0..500))
Now assuming that your controller action takes an id parameter:
public ActionResult SomeAction(string id)
{
...
}
the value of this parameter inside the action will be (refine_1=cgid=womens&refine_2=c_refinementColor=Black&refine_3=price=(0..500)).
You could bring this even a step further and write a custom model binder that will parse this value and bind it to a view model containing those properties that your controller action could take as parameter instead of a id string parameter.

what is a good way of passing parameters to SimpleJdbcTemplate

being pretty new to Spring and Jdbc, I am looking at a code from a Spring book and it is like this:
public voidaddSpitter(Spitterspitter){
jdbcTemplate.update(SQL_INSERT_SPITTER,
spitter.getUsername(),
spitter.getPassword(),
spitter.getFullName(),
spitter.getEmail(),
spitter.isUpdateByEmail());
spitter.setId(queryForIdentity());
}
Ok, so first param should be my SQL statement, but for the second param well does it get ugly in the code if there are like 15 columns in my table and I want to write 15 lines of those .get() methods? is there any nices/cleaner way of passing these?
Get the values into an Object List (in a helper method ?) and convert it into an array while passing to update().
For eg:
List<Object> insertValues = new ArrayList<Object>();
....
insertValues.add(spitter.getUsername());
....
jdbcTemplate.update(SQL_INSERT_SPITTER, insertValues.toArray());

Best way of implementing DropDownList in ASP.NET MVC 2?

I am trying to understand the best way of implementing a DropDownList in ASP.NET MVC 2 using the DropDownListFor helper. This is a multi-part question.
First, what is the best way to pass the list data to the view?
Pass the list in your model with a SelectList property that contains the data
Pass the list in via ViewData
How do I get a blank value in the DropDownList? Should I build it into the SelectList when I am creating it or is there some other means to tell the helper to auto create an empty value?
Lastly, if for some reason there is a server side error and I need to redisplay the screen with the DropDownList, do I need to fetch the list values again to pass into the view model? This data is not maintained between posts (at least not when I pass it via my view model) so I was going to just fetch it again (it's cached). Am I going about this correctly?
Your best bet is to create a SelectList in your Controller - use my extension method here:
http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc
Pop that into ViewData using the same key as your property name:
ViewData["statusid"]=MySelectList
Then just use Html.DropDownFor(x=>x.StatusID) and you're all set.
Answering in parts:
The best way IMHO is to pass the list in the ViewModel like this:
public SelectList Colors
{
get
{
// Getting a list of Colors from the database for example...
List<Color> colors = GetColors().ToList();
// Returning a SelectList to be used on the View side
return new SelectList(colors, "Value", "Name");
}
}
To get a blank or default option like ( -- Pick a color -- ), you can do this on the view side:
#Html.DropDownListFor(m => m.Color, Model.Colors, "-- Pick a color --")
You'll have to fetch/populate the list again if it's part of the ViewModel.
Take a look at the following blog post. It can give you some tips:
Drop-down Lists and ASP.NET MVC
You could do something like:
<%= Html.DropDownListFor((x => x.ListItems), Model.ListItems, "")%>
or
<%= Html.DropDownList("ListItems", Model.ListItems, "")%>
The last param 'optionLabel' makes a blank list item
In this case, you can see ListItems is a property of the model.
I have made the view strongly typed to the model also.
(You know this already!)
Pass the list in your model with a SelectList property that contains the data
Yes, add it when you build the SelectList. (If you build the list using LINQ, Union might come in handy.)
Yes do do, and yes you are.
I find it more intuitive to work with a sequence of SelectListItems (rather than a SelectList).
For example, this would create an IEnumerable<SelectListItem> from a sequence of customer objects that you can pass to the Html.DropDownListFor(...) helper. The 'Selected' property will optionally set the default item in the dropdown list.
var customers = ... // Get Customers
var items = customers.Select(c => new SelectListItem
{
Selected = (c.Id == selectedCustomerId),
Text = c.Email,
Value = c.Id.ToString()
});

Resources