View with multiple partial views posting back - asp.net-mvc-3

I'm new to MVC (MVC3) so not sure about the best way to implement this.
I want to create a single "main" view (not strongly-typed). This "main" view will contain multiple strongly-typed partial views that each contain a form. Each partial view will therefore post back to their own POST action that does whatever. The problem I see is that when a partial view posts back, it needs to only update the partial view itself and not affect the other partial views on the page.
When I postback from a partial view now, it just returns the partial view alone back, rather than the entire "main" page.
How can this functionality be achieved in MVC3? (from a high-level perspective)
Thanks

You can post data by AJAX.
In my example I use jQuery:
<div id="first-form" class="form-container">
#Html.Partial("FirstPartial")
</div>
<div id="second-form" class="form-container">
#Html.Partial("SecondPartial")
</div>
// and here go rest forms
Your partial view may be following:
#model YourModelClass
#using (Html.BeginForm())
{
// some fields go there
}
<input type="button" value="Save Form Data" class="save-button"/>
Js would be following:
$("input.save-button").on("click", function () {
var button = $(this);
var container = button.closest("div.form-container");
var url = container.find("form").attr("action");
container.busy($.post(url, function (response) {
container.html(response);
}));
return false;
});

Related

Update the data in View with AJAX not working

I have diffrent <a> tags that normally pass a parameter to an action using asp-route="". Now i want to use AJAX t do this. each tag is supposed to pass an ID that comes from the model chats when the page loads up. (asp-route-ChatID="#Model.ID").
How can I achieve this in AJAX and pass that parameter? I tried using Data-ajax-update and Data-ajax-url but these option arent even available in Intellisense. Here is the method that i want to call
public IActionResult Chat(string ChatID)
{
Chats userchats=new Chats(); // a class that holds chats
//selecting data from the database......
return View(userchats);//returns view with the model
}
here is the <a> tag that gets clicked and it needs to pass a specific ID that comes from the model
<a > View Chat </a>
here is the <div> that needs to be updated depending on what <a> is clicked
<div id="UpdateThis"> <!--show data that comes from the method ajax calls--> </div>
How can I implement ajax here with tag helpers or any other way?
Use PartialView instead of view if you want to update div.
public IActionResult Chat(string ChatID)
{
Chats userchats=new Chats(); // a class that holds chats
//selecting data from the database......
return PartialView(userchats);//returns view with the model
}
View
<a id="btnView" data-id="1">View Chat</a>
<div id="UpdateThis"></div>
<script>
$("#btnView").click(function () {
$.post('#Url.Action("Chat")', { ChatID: $(this).data("id") }).done(function (e) {
$("#UpdateThis").html(e);
})
});
</script>

mvc4 Razor Ajax Call to show partial view

Am trying to get a partial view to render with an AJAX call. The following ActionResult is in my base controller which is inherited by all other controllers in the solution:
public ActionResult FileManager()
{
return View("_FileManagerPartial");
}
and the folowing code is another partial that sits on the page
#Ajax.ActionLink("File Manager", "FileManager", new AjaxOptions { UpdateTargetId = "dvFilemanagerContainer" });
dvFilemanagerContainer is a div in the layout view and the partial view "_FileManagerPartial.cshtml" is in the shared views folder.
When I click the link for the ajax call, instead of loading the intended partial view it loads a duplicate of the page into the div.
Any ideas?
Edit
PartialView contents its currently just the following
<div id="dvFilemanagerWrapper">
File Manager
</div>
change your controller to
public PartialViewResult FileManager()
{
return PartialView("_FileManagerPartial");
}
In View add this line, so that with partial view, the master layout is not rendered, only partial view is rendered:
#{
Layout = null;
}
<div id="dvFilemanagerWrapper">
File Manager
</div>
Problem was to do with how my RouteConfig was handling the call. Have created a new MapRoute to point it to the right place and is now working. Thanks for help guys.

Update partial view after edit

I have the following index:
<div id='addProduct'>
#{ Html.RenderPartial("Create", new BoringStore.Models.Product()); }
</div>
<div id='productList'>
#{ Html.RenderPartial("ProductListControl", Model.Products); }
</div>
The partial Create view contains an invisible div which is used to create a new product.
After doing so the partial view ProductListControl is updated.
Now I want to do so with an edit function.
Problem: It's not possible to integrate the edit page while loading the index because at this moment I don't know which product the user wants to edit.
My thought:
I'd like to call my existing edit view in an jquery modal (not the problem) so the user can perform changes.
After saving the modal is closed (still not the problem- I could handle this) and the ProductListControl is updated (here's my problem ... :().
How am I able to do so?
I've seen some tutorials but I'd like to keep it as clean & easy as possible.
Most of them are using dom manipulating and get feedback from the server (controller) by a JsonResult.
If possible I'd like to stick to the razor syntax, no pure JavaScript or jquery and if possible I'd like to avoid JsonResults.
One way might be to use the Ajax.BeginForm for your create product view.
The Ajax.BeginForm accepts a number of AjaxOptions, one being the UpdateTargetId (your DOM id, in this case your productlist div), more info here.
Then in your product controller code you can return a partial view, with the product list. So for example:
Index.cshtml
#using (Ajax.BeginForm("AjaxSave", "Product", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "productList", InsertionMode = InsertionMode.Replace }))
{
// your form
<p>
<input type="submit" value="Save" />
</p>
}
...
<div id="productList">...
</div>
ProductController.cs
[HttpGet]
public ActionResult AjaxSave(Product product)
{
if (ModelState.IsValid)
{
// save products etc..
}
var allProducts = _productService.GetAllProducts();
return PartialView("ProductListControl", allProducts);
}
There is a nice article on about this here.

MVC3: Button action on the same view

i wish to change the inner html of a view on button click but maintain the view. I know how to change the html content of a div in javascript, but how can I have the action of the button not return a different view?
My buton looks like
<input type="submit" value="submit" onchange="myfunc()"/>
where myfunc() is the function in Javascript changing the div content.
Assuming you want a link to render content using ajax (and hopefully using razor) you can do something like the following:
First, setup the action to render the content partially. this can be done a few ways, but I'll keep with the logic in the action (and make it callable directly or by ajax):
[HttpPost]
public ActionResult Save(SomeModel model)
{
/* build view */
return Request.IsAjaxRequest() ? PartialView(model) : Wiew(model);
}
Next, setup a container in your page where the content will be populated along with the form you're looking to submit. If you want the form to disappear on a save, wrap it in the container. Otherwise, keep the container separated. In the below example, the from will submit and on success it'll come back, otherwise the new content will appear in its place:
<div id="ajaxContentPlaceholder">
#using (Ajax.BeginForm("Save", new AjaxOptions { UpdateTargetId = "ajaxContentPlaceholder" })) {
<!-- form elements -->
<input type="submit" value="save" />
}
</div>

MVC3 Ajax.BeginForm with PartialView and persistent routedata issue

I have a main view and the URL for this view has a Action/Controller/Area and id value, something like:
http://localhost:56513/Incident/IncidentHome/Index/8c02a647-a883-4d69-91be-7ac5f7b28ab7
I have a partialview in this main view, one that calls methods in the controller via Ajax. This partial view needs to know the ID value of the url for the parent page. I found how to do this is through 'ParentActionViewContent'. Something like:
using (Ajax.BeginForm("UpdatePersonalStatusPanel", "Status", new { area = "Tools" , id = ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() }, new AjaxOptions { UpdateTargetId = "divPersStatus" }))
{
<p style="text-align: center;">
<span class="editor-label">#Html.LabelFor(m => m.StatusText)</span> <span class="editor-field">#Html.EditorFor(m => m.StatusText)</span>
<input type="submit" value="Change Current Status" />
</p>
}
Now, this works fantastic for calling the controller method. The ID is passed correctly so that the controller can then see it in the routedata. I use the id to perform a database call, and then return the partialview again. The problem is on the return. I get a 'Object reference not set to an instance of an object' on the ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() bit in the ajax.beginform , and my targetid doesn't refresh.
Clearly I must be doing something wrong. Does someone else have a better way to see the parent view's routedata through Ajax?
If I'm understanding you correctly, this partial view calls itself. So ParentActionViewContext works the first time because the first time your main view calls an action using this partial view. However, later an ajax call directly returns this partial view. When the partial view is invoked directly there is no Parent View action hence the null reference on ParentActionViewContext.
Rather than deal with with route data I recommend including the id in the model of your partial view.
new { area = "Tools" , id = Model.Id }

Resources