Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an application which uses MVC and KnockoutJS. In my application is a grid in a view which shows a knockout observable array bound as data to a html grid.
I want to navigate to another view when a user clicks on any of the row from the grid. When a user clicks on any row I capture the id from that row, and call a javascript method which uses Ajax to invoke an action method from a controller.
I am able to call the action method from javascript method using $.ajax, but I am not able to redirect to the other view.
How can this be done?
You can handle the success callback and call window.location.href to the action method which will return your view
$.ajax({
type: "POST",
url: url,
data: data,
success: callbackmethod,
dataType: dataType
});
function callbackMethod() {
window.location.href = "/YourController/YourView"
}
In the Controller
public ActionResult YourView()
{
//Any processing
return View(YourViewModel);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to submit data using partail View.How do I do it? Can someone send simple sample code for understand it?
I want to create comment box as partail view.
If you give your Html here, it would have been helpful.
I recommend that you use the ID of the <input> tag and SUBMIT the value of it to your server via ajax call.
var comments = $('#Comment_Box_ID').val();
$.ajax({
type: 'post',
url: '/controller/method/',
data: comments,
success: function (data) {
// success code
},
error: function (e) {
// error code
}
});
I am using MVC3, C#, Razor, EF4.1, SQLServer 2008.
I have a parent form with a dropdown for "Suppliers". I wish to add a "quick add" link/button that enables the user to quickly add a supplier to the DB which is then available in the dropdown for selection. At present this is achieved by
Parent Page -> Add Supplier Page -> Parent Page(Page Refresh)
Of course on return to the parent page, it refreshes and removes all non saved data - which is a problem. It would be better to have a popup window which then saves the suppliers and then just refreshes the dropdown portion of the parent page form. So I believe I am seeking an approach to:
Parent Page -> Popup(Modal) -> DB Save -> Refresh DropDown in Parent Page (Ajax???) -> close Modal popup.
I would appreciate guidance on the above, as I am a little stuck on the best practice and hopefully simple approach to this.
Many thanks.
I normally do something like this:
Create an 'Add' button that will display a popup. (I use jQuery dialogs. They are simple, free, and easily to implement by just calling .dialog on a div). Inside this dialog have the appropriate fields needed to create a new supplier. Have a 'Save' button in this dialog and have it wired up to a AJAX post. (Again this is very simple using jQuery)
If you do use jQuery its as simple as submitting that form to your controller action that will then call you data access layer to save the new supplier entity. When the AJAX call comes back successfully you can reload the contents of the supplier grid with another AJAX post. All the 'Magic' comes from implementing AJAX really which will allow for you to retain the users input and not reload the whole page. The AJAX call that is executed after the user enters in a new Supplier and clicks save would look something like this:
In your JavaScript:
$.ajax({
url: "ControllerName/SaveNewSupplier",
Data: $('#YourAddNewSupplierFormName').serialize(),
Type: "POST"
Success: function(result) {
// this is what will get called after a successful save and return of your action method on your controller. This is where you will put the call to repopulate the supplier list with the updated list.
UpdateSupplierList(); // This function is created below
}
});
In your controller:
Public JsonResult SaveNewSupplier (NewSupplierModel newSupplier)
{
// save your new supplier through your data access layer
// if save is successful then return
Return Json({success = true}, JsonRequestBehavior.AllowGet)
}
Then to repopulate the initial div that contains all the suppliers do something like this:
In JavaScript:
function UpdateSupplierList()
{
$.ajax({
url: "ControllerName/GetAllSuppliers",
Type: "GET"
Success: function(result) {
$('#SuppliersDiv').html(result.suppliers)
}
And in your controller:
// remember that a lot of this is pseudo code and your will have to implement it better for your situation. But basically its just:
Public JsonResult GetAllSuppliers()
{
var suppliers = db.GetSuppliers()
return Jason({suppliers = suppliers}, JsonRequestBehavior.AllowGet);
}
EDIT: If you are updating a SelectList via jQuery then this article is almost identical to what I explained but goes into much more detail on updating the select list. Hope this helps.
http://www.joe-stevens.com/2010/02/23/populate-a-select-dropdown-list-using-jquery-and-ajax/
This is kind of a unique issue, and I'm still fairly new to MVC, so I'll do the best I can to explain it. I have a page with a third party grid, where each row is a "Company" object. My model for the view is a CompanyManager object, with the search parameters as fields and the list to populate the grid. Users are able to select a row for editing, which brings up a popup. A button outside the grid also opens the same popup for creating a new record.
The content of the popup is in a partial view, AddEdit, and the model for it is the "Company" object. Along with other fields, there is also another third party grid with "Contacts" as records. From the third party grid of "Contacts", I can serialize the records and pass them along on submit.
My problem lies with submitting on the modal popup, which should close when successful and stay open when the Company model (or any Contacts in the grid) fails validation. What's the best way of going about the submit? Currently, I have a button that calls a JavaScript function. In this function, I've tried jquery $.submit, but since the form posts to Index, that would close the popup regardless. I've also tried $.post to post to an Ajax call, but I have a JSON result being returned in the controller for this, which didn't work as I expected- it just outputs the JSON as HTML.
If you do your ajax call with JQUERY like this:
$.ajax({
type: 'POST',
dataType: 'json',
url: '/url/', //url your posting to
data: $('#form-addedit').serialize(), //serialize the data in your form
success: function (result) {
//hide modal
}
});
You should get the JSON Result in 'result'. Notice the dataType says 'json' if it was 'html' it would expect html to be returned. The result will be put into the variable result in the success function call and you can do what you want with the variable then, and determine if you need to close the modal or not.
Also, make sure in your controller, that you are indeed receiving an ajax call - Request.IsAjaxRequest()
You can do this by having a regular button to submit the form, like you would on any in-page form. Set the id of the button, let's say to 'Submit'.
Then validate the form with jQuery and the .click function. Something along the lines of
$("#Submit").click(function () {
var value = $("#your_field").val();
if (/*check for invalid condition*/) {
$("#Error_message").show();
return false;
return true;
});
This should check the value of each field you need to validate. If the validation fails, show the user and error message and return false. This prevents the click event (form submit) from executing. If the validation checks pass, return true to allow the click event which will submit the form and close the window.
In the file FirstView.cshtml I have an event - clicking to a cell of a table redirects you to a method:
$.get('#Url.Action("MyMethod", "MyController")', { someParameters });
In the method MyMethod, which is void, I call and event DownloadStringCompleted in which I have:
Response.Redirect(Url.Action("Second", "MyController"));
Second is an action method which returns SecondView. SecondView is my desired view but it never shows on the browser. The breakpoint enters in it, passes it and I get FirstView in the browser.
What could be the reason? Can it be because they are in the same controller?
The methods are like this:
Second return View. In its body, I pass some ViewData parameters.
The event:
I read some JSON data and call the redirection.
The strange thing is that the breakpoint moves through the correct view, but I get the wrong one in my browser.
Srcee,
I believe this is due to the fact that your ajax function is 'done' once it has hit the MyMethod action. The redirect doesn't get fired as it's not part of the pipeline due to the ajax call (at least, this is my basic understanding). An alternative for you would be to do something along the following lines:
$.ajax({
url: '#Url.Action("MyMethod", "MyController")',
data: { id: 123 }, // i.e. someParameters
context: document.body,
success: function(){
window.location = '#Url.Action("Second", "MyController")';
}
});
this is all top of the head stuff and may not work, but is an alternative approach.
[edit] - based on your later edit, i would actually suggest that you don't use ajax at all as it's impossible (as per my comments below) to redirect on the server via an ajax call. see:
asp.net mvc ajax post - redirecttoaction not working
and also:
How can I RedirectToAction within $.ajax callback?
for confirmation on this.
Try not calling Response.Redirect(...) in MyMethod. Instead, call:
public ActionResult MyMethod()
{
return Redirect(Url.Action("Second"));
}
Note that if the controller name is the same as the one you are in, you don't need to explicitly include it.
I just did a test on my dev box, and this works (assuming I correctly modeled your problem).
I inherited an MVC app and am a true novice at it coming from an ASP.NET environment. My problem is I can't manage to move variable data between my partial views and controllers. In ASP.NET this was pretty straight forward, not the case in MVC. So the following code fires when a Tab is selected from the client but I need to capture the selectedTabIndex value from the client and pass it to the controller.
function onTabSelect(e) {
var selectedTabIndex = 0;
selectedTabIndex = $(e.item).index();
alert(selectedTabIndex);
}
I considered using the ViewData object but there doesn't appear to be a way to make perform this task of assignment from within the function. So the following code would seem to be a ridiculous task and it fails anyway. (Remember, I am an extreme novice at this)
function onTabSelect(e) {
var selectedTabIndex = 0;
<% =ViewData["selectedTabIndex"]%> = selectedTabIndex;
}
I also considered using cookies but that doesn't seem to be a practical method either. In ASP.NET I could access the client controls using the .find method but this is a steep learning curve for me.
What are my alternatives?
If different tabs can be selected by the user between Save operations, you might need to consider binding some kind of click function (using jQuery) to set the selectedTabIndex javascript variable. Alternatively, you could set a hidden input's value to the selected tab index.
In either case, if you need the value in your controller (to set ViewData, ViewBag, some model data, etc) when a Save operation is submitted, you could submit the data via $.ajax and return some JSON from your controller
$('#SaveButton').click(function() {
$.ajax({
url: '/Controller/Save',
type: 'POST',
// you might need to serialize additional data you want to save here
// but you could create any JSON object before calling $.ajax
data: {"selectedTabIndex": selectedTabIndex}, // data to POST
dataType: 'json', // this indicates the type of data returned from controller
success: function(data) {
// you didn't really describe how to programatically set a tab,
// so "setToTab" is a guess
$('#tabID').setToTab(data.selectedTabIndex);
}
});
}
And your controller might look something like
public ActionResult Save(int selectedTabIndex)
{
// again, you might need different parameters to complete your Save
return JsonResult(new { selectedTabIndex: selectedTabIndex });
}
Data is sent to a controller via a HTTP POST. Create a hidden input <input type="hidden" name="selectedTabIndex"/> and set the value with javascript prior to POST. The controller can extract this value from the Form parameters, or it can be autopopulated in the Action method if the method contains a parameter matching the input name.
This is a non-ajax alternative to the answer provided by David.