Update partial view after submit Ajax.Beginform - c#

I am new at .NET mvc.
In a view "DisplayThings" I have something like:
#foreach (var thing in Model)
{
#Html.Partial("DisplayPartial", thing)
}
In the partial view "DisplayPartial" I have
#using (Ajax.BeginForm("Afunc", new AjaxOptions ()))
{
#Html.EditorFor(model => model.AstringThing)
#Html.EditorFor(model => model.AintThing)
<input type="submit" name="submit" value="Ajax Post" />
}
At the moment the "Afunc"-Action saves the model to the database and then redirects to a controller action to retrieve all "things" from the database and render the entire "Displaythings" View.
My question is: When i press one of the submitbuttons (There is one submitbutton for every "thing" i the list). I want only that partial view to reload/reflect on my change. I dont want to reload the entire "Displaythings" view. How do I do this? If I just return a partial view I lose everything else but that partial view.
If this is a bad approach please give me directions.
Update:
I am still doing something wrong as I get the partial view rendered in a new page. My controller :
public ActionResult Afunc(ThingModel thingmodel)
{
// do
return PartialView("DisplayPartial", thingmodel);
}
I have tried using UpdateTargetId and onsuccess both with the same result (A new page)

In the AjaxOptions that your are simply now passing as new AjaxOptions you can specify the target element using the UpdateTargetId property:
<div id="unique_thing_id">
#using (Ajax.BeginForm("Afunc", new AjaxOptions { UpdateTargetId = 'unique_thing_id' }))
{
}
</div>
Above, a container with unique id for every "thing" is represented with <div id="unique_thing_id">. This will be replaced with the repsonse of the request. Change Afunc to render only the particular "thing" partial.

Related

Update only the partial view [duplicate]

I want to show a success message after calling the following ajax.beginform
from Index view
#using (Ajax.BeginForm("Insert", "Home", new AjaxOptions() { UpdateTargetId = "result", HttpMethod = "POST" }))
{
#Html.TextAreaFor(m => m.openion)
}
this is my result div
<div id="result">
</div>
and my controller is
[Httppost]
public ActionResult InforMessage(openionModel usr)
{
return Content("Thanks for adding your openion");
}
but when i try this it is going to another view InforMessage
It is not updating the result div.
There is no Informessage Exist. Still it open a new page with message
"Thanks for adding your openion".How to solve this?
If your redirecting to another page its because you do not have the correct scripts loaded (or have duplicates or have them in the wrong order) so its doing a normal submit.
Ensure you have included (in order)
jquery-{version}.js
jquery.unobtrusive-ajax.js

Complex Views containing multiple Partial Views in ASP.MVC

I have a following form:
Edit is some partial view _Edit with separate view model called EditVM.
Search is a partial view _Search split between two another partial models - filter (_SearchFilter) and search results (_SearchResults). All those views share one view model SearchVM.
Finally I'm trying to make an UpdateVM which represents what's on the picture. It contains EditVM and SearchVM instances.
My problem is loosing information about the UpdateVM.
First I'm calling get action Update.
[HttpGet]
public virtual ActionResult Update()
{
var model = new UpdateVM();
var searchVM = new SearchVM();
model.searchVM = searchVM;
var editVM = new EditVM();
model.editVM = editVM;
return View(model);
}
View looks like that:
#model UpdateVM
#Html.Partial(MVC.Shared.Views._Search, Model.searchVM)
#Html.Partial(MVC.Shared.Views._Edit, Model.editVM)
Problem begins with searching on the filter. As you can see to the _Search partial view only a SearchVM is passed. I want Search to be generic, shared between the views, so I can't pass to it the UpdateVM.
Filter view _SearchFilter looks as follows:
#using (Html.BeginForm(Model.SearchButtonAction, Model.SearchButtonController, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="frm_row">
#Html.TextBoxFor(model => model.Query)
<input type="submit" value="Search" />
</div>
}
The problem is that post action is getting SearchVM instance, moreover with only Query field set. Is it possible at all to split whole view shown on the picture only between two actions, get and post, with UpdateVM? Is it possible to don't loose the information already stored in the models (search has some settings, for example mode small or big)?
Or maybe there's other way to implement mentioned view in a robust way? Maybe I'm trying to do it not in the MVC style?
You don't want to load your partial views into the main view. you want them to be dynamically loaded based on the search parameters. To do this use an ajax call
$(document).on('click', '.btnSearch', function(){
$.ajax({
url: '#Url.Action("Search", "Controller")',
type: 'post',
cache: false,
async: true,
data: { id: $("#Query").val() },
success: function(result){
$(".divSearch").html(result);
}
});
});
your controller would look like this
public PartialViewResult Search(int id){
var Model = //populate the model based on the selected id
return PartialView("_partialName", Model);
}
and change your search button to
<input type="button" value="Search" class="btnSearch" />
you don't want to submit the form so you want a button instead of a submit and you need to add a class to the button that your script can trigger off of for the click event. Let me know if you have any questions.

redirect to different view after loading partial view in Main view

I dint find answers to this and tried several ways. any help would be appreciated thanks !!
I have view which updates the page without reloading on each click using ajax scripts. Below is the code. but after entire partial views are generated, I want user to redirect complete different view on clicking a link which is not associated to controller user is in now.
my View
#model IMONLP.Models.Search
#{
ViewBag.Title = "Search";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("Search", new AjaxOptions() { UpdateTargetId = "results"
}))
{
<br />
#Html.TextBoxFor(m => m.search_text, new { style = "width: 200px;" })
<input type="submit" value="search" />
}
#Ajax.ActionLink("Try Demo", "PLNHK", "PLNHK", new AjaxOptions { })
// this ajax link should redirect to different view,
<div id="results">
#if (!String.IsNullOrEmpty(#Model.search_text))
{
Html.RenderPartial("Searchprocess", Model);
}
</div>
My controller:
public ActionResult Search(Search s)
{
//do something
return PartialView("Searchprocess", s);
}
public ActionResult Selected(Search s)
{
//DO something
return PartialView("Selected", s);
}
The above "TryDEMO" "PLNHK" ajax action link will have to be redirected to new controller and new action and return view thats returned by that action. everytime I click on that, I found it moving to that controller and then to corresponding view but again its getting back to old page. I used #html.actionlink instead of Ajax, but now I get this error
The "RenderBody" method has not been called for layout page "~/Views/PLNHK/PLNHK.cshtml".
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
EDIT : I did create PLNHK.cshtml. while I'm trying to debug this, the control goes to PLNHK controller then to PLNHK view(PLNHK.cshtml) parses each and every step in that page, but finally I would get the output to be the older page. I was thinking may be the Ajax scripts on before page is the reason.

Get the model of a partial view and use it in an action link

Let's say that I have this view:
#{
ViewBag.Title = "Send Items";
}
<h2>Sent Items</h2>
<p>
#using (Html.BeginForm())
{
Html.RenderAction("AdvancedSearchEngine", "PartialViews");
}
#Html.ActionLink("Back to Selection", "MenuSelection")
</p>
I want to add an html ActionLink that will get me to another view. I want to get all the model used in the partial view in this actionlink to create the list of items that will be displayed in this view.
Something like #Html.ActionLink("See the results", "DisplayItems", new {_myObject = "blablabla"}).
Is there any way to do that?
EDIT
I have added this method:
#Html.ActionLink("See the results", "DisplayItems", "DispatchItems", new { model = Model }, null);
But once the method actually hits, the object is still null.
Create a new action in your controller:
public ActionResult DisplayItems(MyModel model)
{
// Do stuff
return View(model);
}
Then use this AcitonLink in the SendItems view:
Html.ActionLink("See the results", "DisplayItems", "ControllerName", new { model = Model }, null);
I'm not sure if I understood completely this problem but lets try.
Use AjaxHelper to do this, makes more sense, and render a partial view. The ActionLink must have some information about the model that you want to show, can be an id or anything else. Then you can render this by clicking the link and without a full page refresh. Don't forget to include JQuery reference at the main view.
#{
ViewBag.Title = "Send Items";
}
<h2>Sent Items</h2>
<p>
#using (Html.BeginForm())
{
Html.RenderAction("AdvancedSearchEngine", "PartialViews");
}
#Ajax.ActionLink("Back to Selection", "MenuSelection", new {id = Model.Id}
new AjaxOptions { HttpMethod ="GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results")
<div id="results"></div>
public ActionResult DisplayItems(int id)
{
// Do stuff
return PartialView("");
}
Hopes this help you!

MVC3 - Ajax.BeginForm and partial view refreshes

Is there a way to refresh a section of a partial view, or should I break that section out into it's own separate partial view? The problem I'm facing is that whenever I submit my form, the entire partial view updates, duplicating my form inputs, but I really only want the "noteList" to update. Here is some more details that might be helpful.
In my project, I have a page broken out into separate tabs, each of them is it's own partial view that is loaded when someone clicks on that tab. The one I'm focusing on at the moment is a notes tab.
Below is the markup and controller that catches the post.
<div id="noteList">
#Html.Grid(Model).Columns(column => {
column.For(x => x.TimeStamp);
column.For(x => x.UserName);
column.For(x => x.Note);
}).Attributes(Style => "text-aligh: center", #Class => "linkGrid")
</div>
<div id="addNoteForm">
<h2>Add New Note</h2>
#using (Ajax.BeginForm("AddNote", "Dispute", null, new AjaxOptions { UpdateTargetId = "noteList" }, new { id = "AddNote" })) {
#Html.Hidden("DisputeID", ViewData["DisputeID"])
<div class="editor-multiline-field">
#Html.Editor("Note", "editor-multiline-field")
</div>
<input type="submit" value="Add Note" />
}
</div>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNote(FormCollection collection) {
if (this.ModelState.IsValid) {
DisputeNote newNote = new DisputeNote(repository.Get(int.Parse(collection["DisputeID"])), User.Identity.Name, collection["Note"]);
repository.SaveForUpdate<DisputeNote>(newNote);
}
var Notes = repository.GetNotesForDispute(int.Parse(collection["DisputeID"]));
ViewData["DisputeID"] = int.Parse(collection["DisputeID"]);
return PartialView("NoteList", Notes);
}
I know breaking it into another partial view will work, but I'm curious if there is another way to do it.
You need another partial view to do it the way you have listed here - you cannot update a portion of a partial view with that same partial view itself. HOWEVER : ) there are other options though - such as just returning JSON.
You could just use a .ajax() call to post the JSON to your controller method to add the note.
See this post for the rough idea:
JSON / MVC (3P1) HttpPost - not getting it to work on my EF class

Categories