send id from view to controller - asp.net

I have a view that receives a Model and displays info of that model.
I have a submit button and when it is clicked i want it to send the id to the method to process it and delete a row that has such id.
How can I do this? I want to use a button not an html link like
#Html.ActionLink("Delete", "Delete", new { id = Model.Id }) |
Thanks!
I tried input type hidden but hasn't worked =(

You can use a form to do this... I don't use razor, but an equivalent .aspx way to do this would be:
<%using (Html.BeginForm("Home", "myaction", new { Id = 1 }))
{ %>
<input type="submit" value="submit" />
<%} %>
This will post to ~/Home/myaction/1
Just call Html.BeginForm with the appropriate razor syntax.

Related

How does #Html.BeginForm() work? and search result in Microsoft ASP.Net MVC 5 tutorial?

I am working on MVC 5 Asp.Net and following this tutorial. I am wondering how the heck does this fetch the result when I click the Filter button?
There comes a point where this code is added in Movie/view/Index.cshtml
#using (Html.BeginForm())
{
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
Now as far as I know, it creates a textbox and a button on screen. But how is this button calling the search(index) function and passing the value of textbox in the function, I could not get this.
It's not a stupid question. #html.BeginForm() works like this. It has some parameters you could add to it like Action Controller FormType htmlAttributes. The way it works is that if you leave it empty it will look for a post action with the same name that on the page you are now, for example if you are in on the login page, it will look for a login post action. I always write what action and controller I want it to access.
#Html.BeginForm("AddUser", "Admin", FormMethod.Post, new { #class = "my_form"}) {
}
So your post action should accept parameters that your form contains, and that can be a Model ie a Product, ViewModel or single string parameters. In your case with the search your action should look like
[HttpPost]
public ActionResult Search(string SearchString)
{
//do something here
}
Please note here, for the search string to be passed into the method. The name of the <input> has to be the same as the parameter your action takes. So our form should be like this
#using (Html.BeginForm("Search", "YOUR CONTROLLER", FormMethod.Post)){
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
Hope this brings clarity.

ASP.NET MVC: on button click, call display multiple ActionResults in different windows

I have a form that has a drop-down list of values and a submit button.
Currently, when you click on the submit button, a stored procedure is called and then the application generates a url and then the ActionResult is a Redirect to a new window. The url is based on the currently selected value in the dropdown list.
Our client wants another button that when clicked, will basically do the same thing, but FOR ALL VALUES in the drop down list.
Basically, on click, multiple windows will be opened, whose urls each based on a value in the drop down list.
I just started working with MVC and research confused me even more. I'm hoping someone can point me in the right direction.
Should I handle this via some sort of loop in javascript? How? Can you give some examples, please?
ASPX Portion:
<div id="MyContainer" class="select-report">
<%
using (Html.BeginForm(MyManager.Query.Actions.GenerateReport(null), FormMethod.Post, new{target="_blank"}))
{%>
<select name="SearchText" class="my-values-select">
<% foreach (var cc in Model.MyCentresList)
{%>
<option value="<%=Html.Encode(cc.Name) %>">
<%=Html.Encode(cc.Name) %></option>
<% } %>
</select>
<input type="hidden" name="SearchType" value="MyCentre" />
<input type="submit" value="Generate" name="EntityName" />
<% } %>
</div>
Code-Behind:
public virtual ActionResult GenerateReport(GenerateReportOperation operation)
{
string entityName = operation.SearchText;
int entityType = (int)operation.SearchType;
string requestID1 = <code here that calls a stored procedure, a value is returned>;
string requestID2 = <code here that calls a stored procedure, a value is returned>;
string urlString = <code here that contructs the URL based on the values of entityName, entityType, requestID1, requestID2>;
return Redirect(urlString);
}
You would have to use JavaScript to open new windows for each individual HTTP request.

passing dropdown's selected value from view to controller

I have a dropdownlist in my asp.net MVC2 view like this:
<% using(Html.BeginForm("temp","Settings")){ %>
<%= Html.DropDownList("drpFields", new SelectList(Model.Fields, "FieldID", "NiceName", whiteout.FieldID))
}
%>
and I want to pass the dropdown selected value from view to controller action. How do I modify this:
<a class="icon-button-success" href='<%: Url.Action("EditWhiteOut", "Settings", new {FieldId = 1}) %>'>
<img src='<%: Url.Content("~/static/Images/update.png") %>' alt="Update" />
</a>
I want to pass dropdown's selected value to FieldId.
If you're willing to use Ajax, you can avoid the form if you want to use jQuery.ajax. You might want to give your anchor a value for its ID property (my example below only uses its class attribute)
But, since you want to do a regular postback, you'll want to use another overload of Html.BeginForm so you can specify an ID attribute for the form (I specified the parameter names in case you're unfamiliar with this overload)
Html.BeginForm(actionName: "temp", controllerName: "Settings",
method: FormMethod.POST, htmlAttributes: new { id = "MyForm" })
And the jQuery used to make your link submit the form will create a standard submit. So, as long as your select list has a name attribute, it's value will be included in the post's payload.
$(function () {
$('.icon-button-success').click(function (e) {
$('#MyForm').submit();
// you might not need preventDefault, but I can't remember if
// it will create a second post or not
e.preventDefault();
});
});
If you wanted to do a redirect anyway (using the $.ajax method), you could always do window.location.href='redirect/link'; inside the success function in the $.ajax call
and what about
this will trigger javascript submit of the form and provide button if js is not enabled
<% using (Html.BeginForm(youraction)) {%>
<select name='myfield' onchange='this.form.submit()'>
<option .... >
...
</select>
<noscript><input type="submit" value="Submit"></noscript>
<%}%>
or using your code:
use jquery to update the value of the submit the value in which case
javascript:
var link = Url.Action("EditWhiteOut", "Settings");
jquery
function toCallOnChange(){
var linkParameter = $("#id of object").val();
$("a.icon-button-success").attr("href", link+"\"+linkParameter ); //which will overwrite default value to current link
}
<a class="icon-button-success" href='#'>
<img src='<%: Url.Content("~/static/Images/update.png") %>' alt="Update" />
</a>

ajax in asp.net mvc 2

I am using the microsoft ajax and the ajax form looks like this
<% using (Ajax.BeginForm("UserListing", new AjaxOptions
{
UpdateTargetId = "results",
OnComplete = "getData"
}))
{%>
<input id="Submit1" type="submit" value="submit" />
<%} %>
Now, i get the getData() js function called upon completion of the ajax request. all i want is that i need to access the response data of this ajax request inside this function and prevent that data being directed to the div with id results.
Thats because i am returning json result from the controller's action method and i need to parse it and display in the div.
script function is :
<script type="text/javascript">
function getData() {
alert("Response is : ");
}
</script>
the div tag is :
<div id="results">
</div>
I do not want to use other than microsoft ajax. kindly suggest me accordingly.
You could try rendering the response of the ajax request in a partial view containing only hidden fields. Then in your js function you can access the hidden fields using jQuery selectors.
So your action would look something like
[HttpPost]
public ActionResult UserListing()
{
List<string> data = GetUserListing();
return PartialView(data);
}
Your partial view will then only contain hidden fields that you render something like:
<% for (int i = 0; i < Model.Count(); i++)
{ %>
<input id="<%: "User" + i.ToString() %>" type="hidden" value="<%: Model[i] %>" />
<% } %>
That will render as:
<input id="User0" type="hidden" value="PeterSmith" />
Then in your javaScript function you can access each of the fields by doing something like:
function getData() {
var user = $('#User0').val();
alert(user);
}
That will show you the first field rendered. But you can enhance it a bit by looping through all the injected input fields.
Corrected this problem by myself as explained above. need some json parsers, currently looking for those..

Use textbox value on submit as a query string variable

How would I take a text box value and use it in the query string on submit? I'd like it to start as this,
/News?favorites=True
and end up something like this after the user enters in a search and clicks search.
/News?query=test&favorites=True
The controller action looks like this
public ActionResult Index(string query,bool favorites)
{
//search code
}
This question is something close to what I'd like to do, but I'd like to use the query string and maintain the existing values in the query string.
Thanks.
Two possibilities:
place the textbox inside a <form> with method="GET"
use javascript to read the value and pass it to the server (with AJAX or window.location to perform a redirect)
Example with a <form>:
<% using (Html.BeginForm("index", "news", FormMethod.Get)) { %>
<label for="query">Query:</label>
<%= Html.TextBox("query") %>
<input type="submit" value="Search" />
<% } %>
Example with javascript:
<label for="query">Query:</label>
<%= Html.TextBox("query") %>
<%= Html.ActionLink("Search", "index", "news", new { id = "search" }) %>
and then in a separate js file:
$(function() {
$('#search').click(function() {
var query = $('#query').val();
// Here you could use AJAX instead of window.location if you wish
window.location = this.href + '?query=' + encodeURIComponent(query);
return false;
});
});
Using Darin's above <form> answer but with Razor markup:
#using (Html.BeginForm("index", "news", FormMethod.Get))
{
<label for="query">Search:</label>
#Html.TextBox("query")
<input type="submit" value="Search" />
}

Resources