Partial View Submit - c#

I have a view with DropDown List, on change of this dropdown list i get the id and fill partial view using Jquery Ajax like this:
$.ajax({
url: '/Edit/Fill',
type: 'POST',
async: true,
data: { ID: ID },
success: function (data) {
$('#Par').html(data);
},
I have a button in my partial view, that saves my data, i want to return to the same page after saving.
[HttpPost]
public PartialViewResult Index(FormCollection All)
{
//My Code
Return PartialView();
}
i also tried to return the same partial view, didn't work??
i want to stay in the same page after the button submit in the Partial view
Any Suggestions?

Your ajax method points to /Edit/Fill, yet your action method is named Index. Don't you mean /Edit/Index? The rest of the code looks fine.

Option1 : if your partial view is not complex view, avoid returning partial view... instead try to return json data from your Ajax call, and bind the json data to parent view using Jquery.
Option2: When you hit save, instead of form submit try to use Ajax call to save your data.
Option 3: a form submit requires the page to reload, so on page load collect drop-down id and do your Ajax call to load your partial view. (you might have to use session data to load right values in your partial view)

Related

Edit ViewBag based on dropdownlist selected

i have some form with dropdownlist, i want when i select that dropdownlist, the value is passed into controller without page reload, and then change that form based on value pased, without page reload too. I have search for reference like ajax, etc, but none works for me. Please help,
I have two action in controller with that view, one to show the form and one to process httppost with that form, do i have to make one more for this?
Thankyou
What you could do is use an Ajax:
-It's be better to use MVC API controller. (Read about Api controller)
-If you want to use the controller then add the path to the routing table
Example:
-Your dropdown list onSelection/Change should trigger your JavaScript function.
-Your javaScript function should contain the following:
-(Read about how to pass json Objects around).
var json = { //You will use json to send your selected value to your controller or api
selectedValue: SelectedValue
}
$.post("//Path for controller/FolderName/Controller/MethodName", json, function (data) {
//Code after data received
if(data.success == true){//display message etc)
});
Alternative:
Create another page with the form and use razor to edit the form.
You could try the $get function in Jquery.
On change event of the drop down you can call a javaScript method to use $get:
Example
$.get(url, function (data) {
$YourDiv.html(data); //re-insert the form into the page
}
https://api.jquery.com/jquery.get/

Send partial view model and Update partial view with jQuery has issues

I use partial view for small model inside other view model. so i send changes of it by grabbing model data from wrapper form and using serializeArray(). then return PartialViewResult from action and finally fill partial view div container by returned result. this is my code:
var modelStr = $("#[wrapperFormName]").serializeArray();
$.ajax({
type: "POST",
url: targetUrl,
cache: false,
data: modelStr,
success: function (sucResult) {
$('#pa_Cnt').html(sucResult);
},
fail: function (result) {
alert("Fail");
}
});
and render partialview in view as this:
#using (Html.BeginForm("[ActionName]", "[CtrlName]", FormMethod.Post, new { id = "[wrapperFormName]", #enctype = "multipart/form-data" }))
{
<div id="[partialcontainerName]">
#Html.Partial("[partialViewName]", [partialViewModelName])
</div>
}
One of issue is after update partial view with returned result don't work any of jQuery event handlers that bind to elements inside the partial and i know event handlers must be declare in main view and not in partial and handlers must be delegated.
Second issue is updated result has new values but some of elements in partial view show old values and i set cache of ajax to false as cache of action with [OutputCache(Duration = 0)].
I'm confusing. Can anyone help me.
Your first issue is because you must re-add your event handers. I assume you are adding your event handlers within $(document).ready or an equivalent when the page loads. After you've refreshed your partial using $.ajax, the original elements that had event handlers no longer exist - their instances have been replaced and therefore the event handlers won't fire. You need to re-add the event handlers as part of the success callback after the line:
$('#pa_Cnt').html(sucResult);
Not sure about the second issue..
I found it. Thanks from #David for first issue. I separate internal actions of delegated events to functions that pointed with variable names and attach delegate events to them after update html of partial with returned result. this is a simple sample:
var sampleHandler = function() { //some code }
and then in ajax success:
success: function (sucResult) {
$('#pa_Cnt').html(sucResult);
$("[parentClassNameSelector]").on("click", '[childSelector]', sampleHandler);
}
About second issue ModelState of MVC is Guilty. :) specially in elements that rendered by mvc helpers. So i decide to do this in controller action.
if (ModelState.IsValid) { ModelState.Clear(); }
I don't know if this is good or has any other issue. For now it was solved my problem. I'm waiting for new comments and advises. Thanks so much.

C# Kendo MVC Tabstrip post model in partial view

I have a tabstrip that is dynamically populated with a set of partial views. Each of these partial views is an entry form, and some of them have differing Entity Framework data models behind them.
I would like to POST the model to the server with two arguments (a targeted tab index and the model data) whenever a different tab is selected. (To save the tab data)
My issue is that clicking on the tab links seems to be a 'get' action rather than a 'post' action, and I'm having trouble figuring out how to submit data both comprehensive and isolated enough. (comprehensive being the model and isolated being the model associated with a PARTICULAR partial view) I assume I could use JQuery to find and execute the click method of update buttons on the partial view, but that wouldn't preserve a target index.
Is the best method to find a way to uniquely identify the form itself and subsequently post it? Anyone have a hint for me here?
I am not sure what the best method is. What I do is wrap the code in my partial with
#using (Html.BeginForm("Action", "Controller"))
{
}
and then just having a submit button click event. That posts back just the information from that partial. If you wanted to send multiple partials to the same action then I would use a hidden field that is set when the tabs are clicked and you should be able to pull that index using a Request.Form["FieldName"]. Hopefully that helps.
Edit:
You can also try an ajax call back to the server
$.ajax({
url: "#Url.Action("Action", "Controller")",
type: 'post',
data: {id: 'hiddenfield', data: 'data', etc},
dataType: 'json',
contentType: "application/json",
success: function (result) {
(do something)
}
});
to send the model this way you will need to add those fields to the data row. If there is a lot of data I would recommend stringifying it. You can put this call in the submit button click events.
Use ajax call as mentioned. It does not matter whether the element is on parent or partial page. Once the html is rendered, any element on the DOM can be referenced.

How do I load views independent of the site.master?

I'm preparing an application I wrote in ASP.Net MVC for some light Ajax-y stuff. Basically, I want users to be able to go to different parts of the page without it reloading.
To do this I want to be able to reload the body of my page.
My site master is broken down into a head body and foot div. I want to be able to use something like $("body").load(whateverlink) to refresh the body, but in my case doing this causes the website to be rendered inside the body.
How can I do this successfully?
EDIT: The page is made up of views, not partialviews. In theory I could go and convert all my pages to partials but I'm looking for a way around that if possible.
Thanks
You can get your controllers to return partial views, using JQuery to do a request and update a div with your page content:
JQuery:
function navigate(url){
$.ajax({
url: "/Home/Index",
cache: false,
success: function(html){
$("#content").html(html);
}
});
}
Controller:
public class HomeController : Controller
{
public void Index()
{
return this.PartialView();
}
}
There is a helpful article on BrightMix which might help. It basically renders a partial to a string, which you could then return as part of a ContentResult.

MVC: Refreshing a grid via jQuery

I have a grid (foreach in view) which is shown based on a GET request.
For the POST request, I want to return a filtered view of the grid. The grid is already a partial view, so just returning the grid is no problem.
However, I am looking for some sample code on how I get my filter conditions (there are quite a few, I would have those selected clientside via dropdowns) back to the controller's POST request.
I'd really appreciate some sample code, client & server side using jQuery as the Javascript library for the client side code.
Thank you!
I write code like this.
var url = '<%= Url.Action("List", new { controller = "ControllerName" }) %>';
$.post(url,
$("#criteria_form").serialize(),
function(data) {
$("#list_holder").html(data);
}
);
The C# part would look like this, if you use Craig's example, note that the action's arguments need to have the same name as in the html search criteria form !
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(string searchtext)
{
// retrieve data here based on searchtext
//return partial view to be used in the grid
return View("_partial", myDataCollection)
}
You can also look into jQuery addons like jqGrid or TableSorter.

Categories

Resources