How to use MVC 4 Form Posts - c#

I've come from a Classic ASP background and have started developing ASP.NET MVC 4 with C#.
Previously in classic ASP I would post the whole form and page to the resulting URL. However in MVC4 I've seen other ways of just updating the partial view.
Basically at the moment on the left hand side of my page I have three different combo boxes with some data in. I have a Submit button that when pressed, I want to search my database and return a list of results from the database to a partial view (I've already got the code working to search the database and populate a list of objects.), so that the whole page isn't refresh.
In addition, for partial views, can then handling paging. For example my query could return 100 records, but the user only wants to display 20 per page giving 5 pages of results. Is this possible ?
Can anybody offer any examples of what I'm trying to achieve.

for updating your partial view you should use an ajax call
$('.btnSubmit').on('click', function(){
$.ajax({
url: "#(Url.Action("Action", "Controller"))",
type: "POST",
cache: false,
async: true,
data: { combo1: $('.Combo1').val(), combo2: $('.Combo2').val(), combo3: $('.Combo3').val() },
success: function (result) {
$(".Content").html(result);
}
});
});
then on your view just put a div with class that matches where it will put the returned partial view. For paging I just use a jquery plugin. Here is a page that has some options http://plugins.jquery.com/tag/paging/ Let me know if you have any questions.

Related

MVC PartialView Cycles Back to Previous PartialView

I have a MVC Controller with an Index that will cycle through multiple PartialView as the user goes through the form process.
Here is the Index:
#section pageMain {
<div id="partialView">
#Html.Partial("SelectAccount", SUPR.Models.Account.GetAccounts());
</div>
}
This works fine and I get the SelectAccount page just fine.
My issue is that I have an AJAX call that runs when the user selects a row in a table on the SelectAccount page. What is supposed to happen is that the PartialView is then replaced with another PartialView that displays the details of the selected row. This actually does work, but after about 1 second it cycles back to the SelectAccount PartialView with a query string attached, for some reason, to the URL.
Before
After
Here is the code for the AJAX call:
$.ajax({
type: "GET",
url: "/Review/GetReviewView",
data: { profitCenter: profitCenterNo }
}).done(function (data) {
$('#partialView').html(data);
});
The ONLY that is happening in the controller for GetReviewView is that I'm returning the PartialView with the PartialView name and model. This working because, in that brief moment that I can see the ReviewAccount view, the proper data is in the fields.
Any thoughts as to why this odd behavior is occurring?
Are you capturing the event in JS? If you are triggering off of a click event then add the event parameter to the method and then at the end of the method add:
event.preventDefault()
And see if it still happens. It sounds like a client side JS issue, not a C# issue.
The way you are doing this is actually fine. There used to be a Microsoft library called ASP-AJAX or something, don't remember because I didn't use it much. This library basically allowed you to decorate HTML elements with ASP-AJAX-METHOD , ASP-AJAX-REFRESH-TYPE and it would automatically do something similar to what you are doing now. Go to the Server and retrieve a PartialView.

How to dynamically add/delete rows in asp.net mvc? [duplicate]

This question already has an answer here:
Submit same Partial View called multiple times data to controller?
(1 answer)
Closed 6 years ago.
I want to have an "add row" functionality in my asp.net mvc View.
One way I can do it is have n hidden rows and unhide a row each time "add row" is clicked. But then how would I handle serial numbers (each row would have a serial number) when a row is deleted.
I don't want to do it with JS. What would be the best approach. Should I do it from code behind? Any suggestions?
I am not sure why you do not want to do it with javascript and everything on the client side. It would be a better experience for the user and it would be quicker.
However, since you specifically indicated you want to do it in code behind then do this. Create a partial view and put the required html for a new row into it. Then you need to call your controller to serve that html to you from the client side. You can do that using AJAX. Here is how with jQuery:
$.ajax({
type: "GET",
url: "/Home/GetSomePartialView/",
data: someArguments,
success: function (viewHTML) {
$("#someDiv").html(viewHTML);
},
error: function (errorData) { onError(errorData); }
});
The above will get the html and inject it into an element with ID someDiv.
You will need an action in controller to serve the html. Here is some code:
public Action result GetSomePartialView(SomeArgumentModel someArguments)
{
return PartialView("_NewRow");
}
Call a webmethod using Ajax that calls the delete SQL for you and rebinds the grid with the new results in JS.

Asp.Net Ajax send ViewModel to Controller

i'm having a little problem here,
I have a table based calendar view that has, on each day, an ajax link that renders some day-specific form to the user to set for the selected day.
Then I want to select the day-specific data on the partial view that opened and save them also using ajax, but I also need to pass some info that is contained in the page model, like the selected day and month, year, etc.
The partial view that is loaded when I click on the day, is going to be the place where the user will chose some hospital duty info, like the duty start-time, the end time, the doctor that is going to be in charge of the duty, and on the page Model, there is the hospital ID, the day month and year of the Duty.
So how can I send the form data plus the page model to a controller that is going to save the data on the database?
Thanks.
i think there are at least 2 ways to do this.
first is on server side.
when you click the main page link,pass the main page model data which the child page need.url like controller/action?a=1&b=2... 1 and 2 are you main page model data.you can get these data in child action by add action method param.then you can pass them to child view use model,viewdata,viewbag
second is on client side.
you can put you main page model data to a js var(or think simply,a hidden input),and then you click the link and show you child page,the child page is part of the main page,so you can read the js var in child page.then you can do some js programe to show the js data in page
so,pass the data from main page to child action,or child page get main page data by js
So how can I send the form data plus the page model to a controller that is going to save the data on the database?
Instead of doing a form post, you could do a ajax post
$.ajax({
url: 'Controller/Action',
type: 'POST',
data: JSON.stringify({
'postData': postData
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: SuccessHandler,
error: ErrorHandler,
});

MVC 4 C# Calendar Widget from Action-View

I have created a web calendar using HTML,CSS and C# in an MVC application. The HTML is in a view and I have a controller with an action that initializes the Calendar and displays the correct days on the view.
It works as intended but the problem comes from the fact that I want to embed this calendar to a couple of pages in unrelated Views controlled by different actions and with different models loaded.
I could copy paste the view code and make the necessary adjustments to the model but that would not be ideal. I tried with RenderAction but the problem is that when I use the buttons to navigate to different months I leave the initial view. e.g.:
#Html.ActionLink("‹", "Calendar",
new { month = Model.RequestedDateTime.Month - 1, year =
Model.RequestedDateTime.Year })
Is there a way to modify this behavior?
Thanks
Html.ActionLink, alway creates a normal link, with have the common behaviour. If you want to share your calender.
To avoid redundant code, you may redesign the calender as a partial view and replace the link by a label for example. Bind an ajax function to the label-click-event to refresh the calender. Something like:
#Html.Label("<", new { onclick="pageMonthBack("+Model.RequestedDateTime.Month - 1+", " Model.RequestedDateTime.Year+");" })
I would place the called ajax functions in a script which is loaded separately.
I solved the problem in a similar way, to what developer10214 proposed. I used a div and in that I used Render.Action. Then I used the following code
$(function () {
$("#cal").on('click', "#backwards", function () {
$.ajax({
url: "Home/Calendar?target=backwards",
cache:false,
type: "GET",
success: function (result) {
$("#cal").html(result);
}
});
});
});
in the including page. And I did not use ActionLink at all.

How to make ajax update panel ? (MVC2)

I am using Telerik tree view control:
http://demos.telerik.com/aspnet-mvc/treeview
http://demos.telerik.com/aspnet-mvc/treeview/clientsideevents
What I want to do is set up this control on the left, then a "panel" on the right, that is a view that updates when the treeview is clicked.
So I want to do AJAX call to retrieve info from DB when a click is made in the tree view. Then I can update the "panel" with information on the current item.
How could I go about building this "panel" ? And any controls that are designed for ASP.NET MVC2 are better as that is what I am implementing this in. I saw something called UFRAME but it reminded me of IFRAME and thought I should probably avoid it.
Can I do this with a partial view, and then just the partial view area of the page updates ?
Thanks.
Telerik TreeView has:
OnSelect client side event that
you want to subscribe to and
issue an Ajax call when select happens
to your Asp.net MVC application controller action that
would return a PartialView which
you can then append to right panel
That's the process to be developed.
I've never used Telerik's controls in my life but based on the documentation on their page it seems that it works this way. Everything is basically the usual Asp.net MVC + jQuery except for the OnSelect client side event that you have to use. So nothing particularly complicated as long as Telerik's controls work as expected (which can be a story of its own).
Some code
Since I've never used Telerik, I still think this can be done something along the line:
You have your TreeView defined in one of your views like:
<%= Html.Telerik().TreeView().Name("ClientSideID") %>
Then use jQuery to do the rest:
$(function(){
$("#ClientSideID").bind("select", function(e){
e.preventDefault();
$.ajax({
url: "SomeURL",
data: e.item,
type: "POST",
success: function(partialView) {
partialView = $(partialView);
$("RightPanelSelector").append(partialView);
},
error: function(xhr, status, err){
// handle error
}
});
});
});
This code isn't tested but will get you started.

Categories