how to use server side button click event in mvc4? - asp.net-mvc

I have to make a textbox somewhere in the page and a button using ASPX View Engine.That page already contains partial views. User will enter his data (code) on textbox and at button click, server code will manipulate that data and show an alert or message that data is processed. How to do that in mvc4?
I have found that we can write server script in page like
<script runat="server">
Protected Sub Button1_Click(sender As Object, e As EventArgs)
ScriptManager.RegisterStartupScript(Me, [GetType](), "showalert", "alert('Message Sent');", True)
End Sub
Private Sub DataProcess(ByVal Data As String)
'Code to check data
End Sub
</script>

You can create a separate Ajax Form ccontaining only this button and the textbox. So you will call an Action in a certain controller then this Action will return a string or a Json. And via an UpdateTargetId property you can display a dialog box. Giving you the code is difficult because I don't know the structure of your code. You can aslo write the Ajax call using Jquery.
This link can help you

Related

MVC controller with void method without JavaScript

Is there a way to call void method in MVC controller without returning blanck page with address controller/voidmethod and without using JavaScript. For example on a page clicking a button to fill a gridview with data which is on the same page.
I know if I leave the button without concrete action on click it will reload the page and perform the Index() method, but I don't think this is the proper way.

How to send parameter in query string on ajax call in asp.net mvc

I want to send the selected page value on the querystring while navigating through paging.
The URL that is generated for paging is like this:
Link/Index?page=2
Link/Index?page=3
But on my URL it only shows Link/Index and performs the Ajax call. But if I disable my Javascript and then navigate through paging it gets Postback and has a URL like
Link/Index?page=2
Which is perfect. But I want this type of URL in an Ajax call as well.
How can I do this? Issue is if we navigate through pages when Javascript is enable it shows Link/Index and when user goes to page no 2 then 3 then 4 and press back button it goes to press page instead of page 3 then page 2.
Here is the code that generates the page links:
<%= Ajax.Pager(
new AjaxOptions {
UpdateTargetId = "divGrid", LoadingElementId = "divLoading"
},
ViewData.Model.PageSize,
ViewData.Model.PageNumber,
ViewData.Model.TotalItemCount,
new { controller = "LinkManagement", action = "Index" }
)%>
This isn't really an issue with the pager, but that's how ajax works. Because you haven't created a new full page request, nothing is stored in history to allow the back button to persist the ajax calls too. You need to use something like jquery.history (http://tkyk.github.com/jquery-history-plugin/) or jquery address api (http://www.asual.com/jquery/address/samples/api/#/section/?id=2.2).

View Master Page and PostBack

I have a dropdown list on my master page that needs to postback after being changed. After the postback, whatever page initiated the postback needs to be re-displayed.
My question is where do I handle this? Obviously I do not want to have to modify every Action in my project... My guess is to maybe postback to some other fixed action and have that action redirect back to the page that is the referrer. Am I correct? Any thoughts?
Thanks.
Jason
In Site.Master, I ended up wrapping the dropdown within its own form that posted back to a dedicated controller/action.
<% Using Html.BeginForm("ChangeRole", "Home")%>
<div id="roleSelector">Change Role: <%=Html.DropDownList("Role", DirectCast(ViewData.Item("Roles"), SelectList), New With {.onchange = "this.form.submit();"})%></div>
<% End Using%>
In the controller I used the following code to change the mode and then redirected back to the referring URL.
<AcceptVerbs(HttpVerbs.Post)> _
Public Function ChangeRole() As ActionResult
Me.CurrentUser.SetRole(DirectCast([Enum].Parse(GetType(Models.ApplicationRoles), Me.Request.Item("Role")), Models.ApplicationRoles))
Return Redirect(Request.UrlReferrer.ToString())
End Function
I am unsure if this is the recommended way but I have been unable to think of another solution.
When you post back from the dropdown list change what are you doing? Can you maybe handle this in a jQuery call thus eliminating the need to re-display the page at all?
Calls to Action Methods can be asynchronous as griegs says, as such, you can post whatever information you need from the radio buttons to an action method without needing to reload the page.
If you need to update a part of the page, you can replace it with the contents of a rendered action method. If you use the jQuery ajax methods, you can post specific information to your methods.
For example, something like this:
$(document).ready(function()
{
$("#myRadioButton").change(function()
{
//Post to your action method, with the value of the radio button, function to call on success
$.post('yourActionMethodUrl', $(this).val(), function()
{
//Update some part of the page
});
});
});
This is based on memory, so you may need to check the syntax.

Jquery UI Dialog Post to ASP.Net MVC Controller Action

I have an MVC view that contains a JQuery UI dialog that can be opened and populated with data.
<div id="dialog">
.... Table of phone numbers
</div>
<div id="personData">
... Person model data
</div>
I am attempting to pass the data from the JQuery UI dialog along with the rest of the MVC View data to a controller action.
public ActionResult Save(Person person, List<PhoneNumber> phoneNumbers)
{
}
In this example the Person type is not part of the dialog and is posted fine. The phone numbers is in the div of the JQuery UI dialog and does not post.
The elements in the dialog are defined in the View and can be seen in the DOM but for some reason something is preventing the data to post along with the rest of the View data. If I remove the .dialog() declaration from the the "dialog" div (now the div is visible on the form), the data (phoneNumbers) will post.
So my question is how do you post the JQuery UI dialog data along with the View data from the form to a controller action? (I know how to post the UI dialog data using a button within the dialog, but I need to post it alongside my main View because of the state issues around this data).
Chances are the dialog box moves the div outside of the form so the fields aren't submitted. You might just link the fields to hidden ones outside of the div or increase the span of the form.
Just as stimms said, you will need to put the data into some fields inside the form you'll be submitting to the action.
Do something like this inside the dialog click function (using jQuery .val())
$("#formFieldName").val() = $("#dialogFieldName").val();
Repeat this for each field.
After that, the fields (probably hidden fields) inside your form will contain the data when you submit the form.

How can I use Html.ValidationSummary with Ajax.BeginForm?

I have an AJAX form that I am creating in my MVC project. If the form is submitted using normal browser function and a page refresh occurs I get validation information rendered in the form (the built in MVC validation based on ViewData.ModelState).
Is there a similiar validation mechanism for AJAX forms?
<% using (Ajax.BeginForm("Create", "GraphAdministration", new AjaxOptions()
{
OnSuccess = "newGraphSuccess",
OnFailure = "newGraphFailure",
HttpMethod = "POST"
}))
{ %>
<!-- some form stuff in here !-->
<% } //end form %>
It really depends on where you are getting the content from to display once the form has been posted. The Validation summary is performed created on the server so that is where you have to do the work.
As an example I was using some partial content in an .ascx file to render a form. You get the form in the page the first time round by calling the action directly with Html.RenderAction
You would have your Ajax.BeginForm etc. in the .ascx file. Then call it directly in an action.
When the Ajax call is made from the browser you get it to post to the same action. That way you can do all of the server side validation that you would normally. You should set up the Ajax call to replace the original form with the new html that is returned by the action.
One thing that you have to be aware of is that the replace JavaScript will replace the content of an element not the element itself so remember to us the id of a surrounding element.
Apologies if that is a little convoluted, if you want more details just comment and I'll flesh out the relevant bits.
Extra Detail:
All of this assumes that you are doing all of the validation on the server.
You are going to have a View that has all of the page stuff in it and then some partial content in a .ascx file, this is where your ajax form lives, it needs to be set to replace content by id. Its easiest if it has the same name as the action your ajax is going to call.
You can use Html.RenderAction to get it into the View. You can also pass in data with other versions of the same method. Your essentially calling it in the same way your ajax code will.
You will need to wrap it all in a div with an id set. Use this id in the partial as the content to replace.
When you render the page the html for the form and all of the ajax stuff will get put in.
When the ajax action is called the partial content will be returned with any validation performed. It will replace the content of the div that you gave the id to.
You can have different versions of the action by using [AcceptVerbs(HttpVerbs.Get)] and [AcceptVerbs(HttpVerbs.Post)] attributes
The main problem with this method is that its not self contained, the div with the id is external to the partial.

Resources