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

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.

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 use MVC 4 Form Posts

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.

MVC button sending parameters from JS

So I have a panel with 3 DDL, 2 TextBoxes, a Cancel button and an Apply button. I want my button work this way:
When I click it, I want it to take the data from 3 DDL and 2 TextBoxes and build a model, send it to my controller/function and refresh the gridview .
But the function also has to check there is no duplicate entries.
So if that function returns a partial view, in case the entry I am adding is duplicated, how can I show a message to display the error?
button:
<button id="btnAddUpdateConfig" name="btnAddUpdateConfig" value="Apply" onclick="ValidateValues()">Apply</button>
My problem also comes before that; how can I send the values to the controller function? Is there a way to call a controller method passing values from the button?
But that method will have to refresh the gridview if the item is added or show and error if it is not.
If I want to do it from JS, how can I do the same?
I just know Ajax.ActionLink and that creates a link when I just want to call a controller method.
how can I send the values to the controller function? Is there a way to call a controller method passing values from the button?
Use jquery ajax call:
function ValidateValues(){
actionUrl=#Url.Actio("ControllerName","Action",new {param1=value,param2=value=param3=value})
$.ajax({
url:actionUrl,
statusCode: {
404: function() {
alert("Data is duplicated");
}
}
});
}
Now you can handle request in your action and if data is duplicate send the following code:
return new HttpStatusCodeResult(404, "Data is duplicated");

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