Using ajax ActionLink in place of Html.ActionLink MVC - ajax

All,
I have an Html.Actionlink that calls a method in my controller and should return a partial view. My partial view is displayed within Index.cshtml, the partial view is _ServerStatusList.cshmtl.
View
#using (Html.BeginForm())
{
#Html.ActionLink("Start",
"StartServer",
null,
new { #class = "startButton" })
}
Controller
[HttpGet]
public PartialViewResult StartServer(Model model)
{
model.StartServer("server01");
return PartialView("~/Views/Home/_ServerStatusList.cshtml", model.Servers);
}
Right now upon clicking the start button all of the functionality works correctly as far as starting the server goes, but it returns the incorrect view. After clicking I get redirected to localHost/home/StartServer and it says "running" (as a started server should say in my server list) on a blank page. Then if I manually navigate to my server status page via the address bar it shows the server is running (as it should say) in my _ServerStatusList.cshtml.
I used an Ajax ActionLink in another part of my project to click a button and return a partial view. I tried it for this button too using this code.
<input id="StartButton" type="image" value="submit" src="~/Images/start.png" alt="Start" height="25" />
#Ajax.ActionLink("Start", "StartServer",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "CurrentView"
}
)
Clicking the button does not work but clicking on the word "start" does something similar to the Html.ActionLink. If I click the Start link it takes me to Index.cshtml, displays running in the area where the partial view should be, but does not load _ServersStatusList.cshtml. Again upon manual redirection everything is as it should be, running and correctly formatted.
How can I have the Ajax ActionLink use the image as the button, and upon clicking the image, return the correct partial view?
Thanks

MVC is smart enough to find the view you need, so change your return PartialView from:
PartialView("~/Views/Home/_ServerStatusList.cshtml", model.Servers);
//To
PartialView("_ServerStatusList", model.Servers);
This should return the correct view :).

Related

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 }

MVC3 Appearing of confirmation message is increasing as geometric progression after each clicking

I have a button. After first click I am getting "Button pressed!" confirmation message. When I press button again I am getting confirmation twice. After third press, message appears four time. In fact I am getting geometric progression. Please help.
View is.
#{
ViewBag.Title = "Home";
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
}
<div id="buttonPressed">
#Ajax.ActionLink("Button", "Index", new AjaxOptions { Confirm = "Button pressed!", UpdateTargetId = "buttonPressed" })
</div>
Controller is.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
When the post comes back you are replacing the contents of the buttonPressed div which contains the button itself. Not a great thing to do.
In addition it is not proper to call back to the Index method which originally displayed the view. That will re-render the page along with the html in the div with an entire rerendering of the view (including all master page stuff), which will continue to happen over and over again.
You need to change the action callback to another action method in your controller, then return a partialView of some html or a string or something else.

Partial rendering in MVC3

I'm trying to render a particular section/div click a particular link or button. Suppose link/button is in the A.cshtml page , and b.cshtml is a partial view that I want to load in A.cshtml page within a particular section/div. I tried Ajax.ActionLink but can't do. Any help or suggestions?
I tried ajaxactionlink but cant do
That's really not the way to ask a question here. Cant do is not a precise problem description. Next time when you ask a question on SO show what you have tried.
This being said, let me provide you with an example:
#Ajax.ActionLink("click me", "SomeAction", new AjaxOptions {
UpdateTargetId = "result"
})
<div id="result"></div>
and then you will have an action which will render this partial view:
public ActionResult SomeAction()
{
return PartialView("_NameOfYourPartial");
}
Finally make sure that you have referenced the jquery.unobtrusive-ajax.js script to your page which uses the HTML5 data-* attributes emitted by the Ajax.ActionLink helper to hijack the click event and send an AJAX request instead of the normal request:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
The controller can return a partial view as action result:
public ActionResult Details()
{
var model = // your model
var viewName = // your partial view name
return PartialView(viewName, model);
}
Ajax.ActionLink should do it, may be you missed somwthing.
Check this post it may give you the answer

multiple button click in asp.net MVC 3

I am having multiple dynamic buttons on my asp.net mvc 3 page. what is the best way to handle button click in asp.net mvc 3? there is no event handling in asp.net, so what is the best practice to hadle.?
You could handle the buttons clicks using javascript by subscribing to their click event. For example with jQuery you could give those buttons a class and then:
$(function() {
$('.someClass').click(function() {
// a button was clicked, this will point to the actual button
});
});
or if those are submit buttons of a form you could give them the same name and different values and then on the server test the value of the name parameter. It's value will equal to the button that was clicked.
Let's suppose for example that you have the following form with multiple submit buttons:
#using (Html.BeginForm())
{
... some input fields
<button type="submit" name="Button" value="delete">Delete data</button>
<button type="submit" name="Button" value="save">Save data</button>
}
Now inside the controller action you are posting to you could determine which button was clicked:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
var button = Request["button"];
if (button == "save")
{
// the save button was clicked
}
else if (button == "delete")
{
// the delete button was clicked
}
...
}
If the buttons do not require the same form data, then you can create two forms with different action methods. This is the easiest solution.
If you need to use the same form data, then there are a number of methods, inclduing Darin and tvanfosson's approaches. There is also an approach based on attributes that will select the correct action method based on which button is clicked.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=724
Depends on what the buttons are doing. If they are logically separate actions, then you could have each postback to a separate action on the server side. This often also works they are variants of the same action, Save vs. Cancel, for instance where Save posts back the form and Cancel redirects to you the previous url (say, going back to details from edit). If the buttons represent different data that would get posted back to the same action, you can give them different values. If the buttons are named, the values will get posted back along with the rest of the form, assuming they are included in the form. If posting back from AJAX, you might need to explicitly serialize the button value along with the form.
Example of Save/Cancel
#using (Html.BeginForm())
{
//...
<button type="submit" class="submit-button button">Save</button>
#Html.ActionLink( "Cancel", "details", new { ID = Model.ID }, new { #class = "cancel-button button" } )
}
Then use CSS, perhaps in conjunction with jQuery UI to style the buttons.
<script type="text/javascript">
$(function() {
$('.button').button();
...
});
</script>

ASP.NET MVC 2 - how to get Ajax.BeginForm work properly inside partial view

I have a View with url like
/Home/SetResults?patientId=[somePatientId]
, part of it gets conditionaly ajax-updated with some partialview
Inside of that partialView I have this code
<% using (Ajax.BeginForm("Action", "Home", new AjaxOptions { UpdateTargetId = "placeholder", InsertionMode = InsertionMode.Replace,HttpMethod = "Post"}))
{%>
<div id="placeholder">
....
Whenever I press submit button I get to my simple controller action-method
[HttpPost]
public ActionResult Action(MyModel model)
{
return PartialView();
}
Everything works fine except the ajax itself - instead of gettin my placeholder updated with the result of controller action I'm always getting redirect to a view with the url of
/Home/Action
So, is it possible to partially update partial view? If yes what I'm doin wrong?
One thing to check would be that you are including the ajax script:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
I've noticed if this isn't included, submitting the Ajax form behaves like a regular submit.

Resources