How to send data through actionlink in asp.net? - asp.net-mvc-3

In the application that I am trying to make, I have a menu in my view as below:
<ul id="menu">
<li>#Html.ActionLink("Create Project", "Display", "CreateDisplay")</li>
<li>#Html.ActionLink("Open", "About", "Home")</li>
</ul>
where CreateDisplay is the name of a controller and Display is a method in that controller which will call another view.
But, I want the Display method to accept certain parameters like username of the person.
In the current view, I have obtained the username as #ViewData["UserName"]
But I am not able to pass these values using ActionLink.
I tried passing the parameters as
<li>#Html.ActionLink("Create Project", "Display?UserName="+#ViewData["UserName"], "CreateDisplay")</li>
but received an exception.
Please suggest some ways of doing this.
Thank you very much in advance.

You need to use the overload that accepts parameters for route values. See the overloaded method ActionLink() here.
#Html.ActionLink(
"Click me!",
"Display",
"CreateDisplay",
new { UserName = "SetYourValHere" },
null);

Related

how to pass parameters to controller from view

I need to pass parameters from a view to control in a form. These parameters are for example a string that is not in a textField. The string is "FATHER" and I send this string from the view to the controller when I click on the submit button in the form. Anyone can suggest how I can do it?
add a hidden input field to your form with a value of "FATHER":
<?= form_hidden('name_of_field', 'FATHER') ?>
and in your controller, get the value when the form is submitted:
$value = $this->input->post('name_of_field');
So if this question is about asp.net MVC ... :
Are you using a strongly typed view, do you have a ViewModel? If so, add a property of type string, say StringToHide, to it, set it to "FATHER" and then, in your form, add
#Html.HiddenFor(StringToHide)
Then the information will be passed to the controller, but it is not editable by the user. And if you're not using a viewmodel yet, well, then you should. It's a clean way to compose all your data when passing from views to controllers and vice versa.
Assuming Asp.net MVC
In View
#{ Html.RenderAction("Menu", "", new { parameterFromView= "FATHER" }); }
In Controller
[HttpPost]
public ActionResult Menu(string parameterFromView)
{
// do whatever
}
In jquery call append the text Father to the URL and accept it in controller.
see code below.
$("#submit").click(funtion(){
window.url = "Controller/Action/" + "Father";
});

Mvc3 implement custom action link

I have .net mvc3 web site. And i must to implement top menu. Each of the menu tags is lead to his action and display another view.This what i have now:
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("Products", "Products", "Home")</li>
<li>#Html.ActionLink("Pricing", "Pricing", "Home")</li>
<li>#Html.ActionLink("Our Team", "OurTeam", "Home")</li>
<li>#Html.ActionLink("Contact Us", "ContactUs", "Home")</li>
</ul><!-- /menu -->
This view is Html.RenderAction("Header", "Home"); in my layout(because it must to appear in all pages)
I need to implement Custom ActionLink. The anchor text must be:
<span>text</span><b>text</b>
The "text" is Home(for example of first li)
And the current ActionLink must add class :"Selected" to the anchor.
How i can do this? Help please
p.s
I can add this menu for each view in my website with "selected" class of current view, but this is not good solution.
If I understand right you want to put the "selected" class to the current displaying action.
You can do a check in the view by looking at this:
HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString()
Then you put the "selected" class to your actionlink the way showed in the previous answer
<li>#Html.ActionLink("Home", "Index", "Home", null, new {#class = ":selected"})</li>
Personally I will create a ViewModel containing a list of "MenuAction" that expose, other than the route values, a bool property "Selected". Imo from the view will be much more cleaner the handling of the data.
You can add class with this ActionLink overload:
<li>#Html.ActionLink("Home", "Index", "Home", null, new {#class = ":selected"})</li>
The 5th parameter is HTML attributes.
MSDN ActionLink of this overload
Update:
$(function(){
var controllerName ='ViewContext.RouteData.Values["Controller"]';
$('#' +controllerName).addClass(':selected');
});

Use DELETE form method in Html.BeginForm()?

I'd like to use the appropriate HTTP method when possible. In this case, when a button is clicked to delete something, I want to fire the controller action with the attribute [HttpDelete]. However, I can't seem to create a form with this method - using Razor syntax. The FormMethod enum does not have an option for Delete and doing the following doesn't override it:
#using (Html.BeginForm("Order", "Users", FormMethod.Post, new { method = "DELETE" }))
Searching for solutions yields none, is nobody doing this? I know I can just use POST but isn't this the point of the HTTP delete method to begin with?
You need this in your form:
#using (Html.BeginForm("Order", "Users"){
#Html.HttpMethodOverride(HttpVerbs.Delete)
}

How to pass both model value & text value to controller in mvc?

I want to pass two values from view to controller . i.e., #Model.idText and value from textbox. here is my code:
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Model.idText
<input type="text" name="textValue"/>
<input type="submit" name="btnSubmit"/>
}
But problem is if i use "Url.ActionLink() i can get #Model.idText . By post action i can get textbox value using FormCollection . But i need to get both of this value either post or ActionLink
using ajax you can achieve this :
don't use form & declare your attributes like this in tags:
#Model.idText
<input type="text" id="textValue"/>
<input type="submit" id="btnSubmit"/>
jquery:
$(function (e) {
// Insert
$("#btnSubmit").click(function () {
$.ajax({
url: "some url path",
type: 'POST',
data: { textField: $('#textValue').val(), idField: '#Model.idText' },
success: function (result) {
//some code if success
},
error: function () {
//some code if failed
}
});
return false;
});
});
Hope this will be helpful.
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Html.Hidden("idText", Model.idText)
#Html.TextBox("textValue")
<input type="submit" value="Submit"/>
}
In your controller
public ActionResult SaveData(String idText, String textValue)
{
return null;
}
I'm not sure which part you are struggling with - submitting multiple values to your controller, or getting model binding to work so that values that you have submitted appear as parameters to your action. If you give more details on what you want to achieve I'll amend my answer accordingly.
You could use a hidden field in your form - e.g.
#Html.Hidden("idText", Model.idText)
Create a rule in global.asax and than compile your your with params using
#Html.ActionLink("My text", Action, Controller, new { id = Model.IdText, text =Model.TextValue})
Be sure to encode the textvalue, because it may contains invalid chars
Essentially, you want to engage the ModelBinder to do this for you. To do that, you need to write your action in your controller with parameters that match the data you want to pass to it. So, to start with, Iridio's suggestion is correct, although not the full story. Your view should look like:
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Html.ActionLink("My text", MyOtherAction, MaybeMyOtherController, new { id = Model.IdText}) // along the lines of dommer's suggestion...
<input type="text" name="textValue"/>
<input type="submit" name="btnSubmit"/>
#Html.Hidden("idText", Model.idText)
}
Note that I have added the #Html.Hidden helper to add a hidden input field for that value into your field. That way, the model binder will be able to find this datum. Note that the Html.Hidden helper is placed WITHIN your form, so that this data will posted to the server when the submit button is clicked.
Also note that I have added dommer's suggestion for the action link and replaced your code. From your question it is hard to see if this is how you are thinking of passing the data to the controller, or if this is simply another bit of functionality in your code. You could do this either way: have a form, or just have the actionlink. What doesn't make sense is to do it both ways, unless the action link is intended to go somewhere else...??! Always good to help us help you by being explicit in your question and samples. Where I think dommer's answer is wrong is that you haven't stated that TextValue is passed to the view as part of the Model. It would seem that what you want is that TextValue is entered by the user into the view, as opposed to being passed in with the model. Unlike idText that IS passed in with the Model.
Anyway, now, you need to set up the other end, ie, give your action the necessary
[HttpPost]
public ActionResult SaveData(int idText, string textValue) // assuming idText is an int
{
// whatever you have to do, whatever you have to return...
}
#dommer doesn't seem to have read your code. However, his suggestion for using the Html.ActionLink helper to create the link in your code is a good one. You should use that, not the code you have.
Recapping:
As you are using a form, you are going to use that form to POST the user's input to the server. To get the idText value that is passed into the View with the Model, you need to use the Html.Hidden htmlhelper. This must go within the form, so that it is also POSTed to the server.
To wire the form post to your action method, you need to give your action parameters that the ModelBinder can match to the values POSTed by the form. You do this by using the datatype of each parameter and a matching name.
You could also have a complex type, eg, public class MyTextClass, that has two public properties:
public class MyTextClass
{
public int idText{get;set}
public string TextValue{get;set;}
}
And then in your controller action you could have:
public ActionResult SaveData(MyTextClass myText)
{
// do whatever
}
The model binder will now be able to match up the posted values to the public properties of myText and all will be well in Denmark.
HTH.
PS: You also need to read a decent book on MVC. It seems you are flying a bit blind.
Another nit pick would be to question the name of your action, SaveData. That sounds more like a repository method. When naming your actions, think like a user: she has simply filled in a form, she has no concept of saving data. So the action should be Create, or Edit, or InformationRequest, or something more illustrative. Save Data says NOTHING about what data is being saved. it could be credit card details, or the users name and telephone...

No output from Html.ActionLink when trying to check Controller name

This is probably a simple oversight but I'm not seeing the problem so I thought I'd ask for some quick help. I'm somewhat new to MVC also (and Razor) so that might have something to do with it also. Basically, here's what's in my Razor View that renders some list items for a navigation bar. I'm just trying to set a class of "selected" on the element if (according to the Controller name) it's the page being requested.
<li>#{ if(Html.ViewContext.RouteData.Values["controller"].ToString() == "AdminHome")
{
Html.ActionLink("Admin Home", "Index", "AdminHome", null, new { #class = "selected" });
}
else{
Html.ActionLink("Admin Home", "Index", "AdminHome");
}
}
</li>
The result I'm getting is just an empty list item element: <li></li>
Any ideas what I'm doing wrong? Is it just a syntax issue?
You need to prefix # before Html.ActionLink. Otherwise MVC treats this as a ordinary method call not a method that outputs html.
<li>
#if(Html.ViewContext.RouteData.Values["controller"].ToString() == "AdminHome"){
#Html.ActionLink("Admin Home", "Index", "AdminHome", null, new { #class = "selected" });
}
else{
#Html.ActionLink("Admin Home", "Index", "AdminHome");
}
</li>
compare the route name in case insensitve like
String.Equals(Html.ViewContext.RouteData.Values["controller"].ToString() , "AdminHome",,StringComparison.CurrentCultureIgnoreCase)
because route name can be in any case. It is what user has typed in url.
For example in url
www.yourdomain.com/AdminHome/Index (controller name is AdminHome and controller will be AdminHomeController)
but with url
www.yourdomain.com/adminhome/index (controller name is adminhome and controller will be AdminHomeController)
Hope this helps.

Resources