How to Hide Parameters of URL in MVC4 - asp.net-mvc

http://localhost:49397/ChildCare/SponsorChild/83
This is the Link ,which is being generated when i click on action link in table and redirecting to Edit Action, now i want to Hide the number '83' in the URL how can i acheive this,
i am using VS2010 MVc4 Razor,
Sorry for my bad engllish
thanks in advance

if you work with links, the links send by GET request to the server, then the parameters are in the url. Might you have two options:
1 - the parameters would have to be on data attributes like data-id="83" and then create a form to send data by post, and creating tags input with attributes data-x, for example:
<a href="my/url" data-id="83> link </a>
then with javascript you need create the form:
<form method="POST" action="my/url">
    <input value="83 name="id" type="hidden" />
</form>
and run the event with JS form submit like: jQuery('form').submit()
2 - you can encrypt and then decrypt get parameters in the controller: How to encrypt and decrypt data in MVC?
Edit
Example for point one:
Html:
<div id="container-generic-form" style="display:none;">
<form action="" method="POST"></form>
</div>
my link
JS:
$(function() { // document ready
var controlAnchorClickPost = function(event) {
event.preventDefault(); // the default action of the event will not be triggered
var data = $(this).data(),
form = $('#container-generic-form').find('form');
for(var i in data) {
var input = $('<input />', {
type: 'hidden',
name: i
}).val(data[i]);
input.appendTo(form);
}
form.submit();
};
$('a.link-method-post').on('click', controlAnchorClickPost); //jquery 1.7
});

We use Two pages like that to hide the variable
public ActionResult RestoreSavedSession(string id)
{
Session["RestoreSavedSession"] = id;
return RedirectToAction("RestoreSavedSessionValidation");
}
public ActionResult RestoreSavedSessionValidation()
{
return View("RestoreSavedSessionValidation");
}
You hit RestoreSavedSession it then takes parameter stores it locally and calls RestoreSavedSessionValidation where it reads parameter from Session or Cache or whatever.

I uses a preview method store the route data to TempData, and route it to the correct action.
public async Task<ActionResult> Preview(string act, string ctl, string obj)
{
TempData["Data"] = obj;
return RedirectToAction(act, ctl);
}
To use it
return RedirectToAction("Preview","Controller",new {act="action",ctl="controller",obj=JsonConvet.SerializeObject(obj)});
After routing
var x=JsonConvert.DeserializeObject<T>(TempData["Data"].ToString());

Related

How can send html text box value with Url.Action to controller action method input argument?

I'm new in asp.net mvc and want to read html text box value and send it to the controller action method argument,for that purpose in view page write this code:
#item.BookName
in url action in this segment:
UserID=html text box value
read value and send it to this action in controller:
public ActionResult Item(int parentPartId,int UserID)
{
}
in view page my text box is this:
<input type="text" id="USERID"/>
How can i solve that problem?thanks.
You can handle the click event of the hyperlink and inject the value from the textbox into it, like this:
HTML:
<a class="BookName" href="" data-id="#item.Id">#item.BookName</a>
Script (assumes you have jQuery, but easily re-writable if not):
$(".BookName").click(function(event)
{
event.preventDefault();
var url = '#Url.Action("Item", "Store", new {parentPartId = "PARENT_ID",UserID="USER_ID"})';
url = url.replace("USER_ID", $("#USERID").val());
url = url.replace("PARENT_ID", $(this).data("id"));
alert(url); //just for debugging
window.location.href = url;
});
You might want to check the input value is valid before you do this, but this will get you started.
Textbox value is dynamic. It depends on user input. Razor tags are compiling at the server and posting to the client.So your razor code can not understand what user going to do to your text area. You need an action trigger the method that includes determining the text box values and send to the server. You can use ajax function.
With Jquery's help.
I think #item is a loop variable.
you can change your code like below
<a onClick="myFunction(#item.id)">#item.BookName</a>
as you see i catch the id and type down as a paramenter.
this is your text area
<input type="text" id="USERID"/>
this is the javascript function that gets the textbox value and sends it to your action
function myFunction(id){
var userId = document.getElementById("UserID").value;
var data ={
parentPartId:id,
UserID:userId
}
$.ajax({ //Jquery stuff
url : '/Store/Item'
type:'POST',
data:data
dataType:'json'
success:function(){//You can handle succes scenario}
});
}
See the data's structure it is a JSON object. And parameter names are same as your actions parameters. When you send it. MVC going to understand the logic and match the parameters and values. )
You need to place form and post your data via model/Form collection
view code
#using (Html.BeginForm("SaveData", "TestCont", FormMethod.Post, new { Id = "frmTest", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="text" id="USERID" name="UserID"/>
}
controller:
[HttpPost]
[ValidateInput(false)]
public ActionResult SaveData(FormCollection form)
{
string html = Convert.ToString(form["UserID"]);
}
make sure to mark [ValidateInput(false)] otherwise it will raise error on posting html
You can place a submit button in form to post it, or in JavaScript use $('#frmTest').submit()

Passing a dropdown selected value to a contorller

I'm playing around in an MVC application and am trying to figure out something that seems pretty straight forward.
I have a Index.cshtml file in my Views/Home/ folder that is pretty simple (below)
Index view
...
<div>
Search
#Html.DropDownList("selection", MyProject.Util.Lists.GetMyList(), "Select One")
#Html.ActionLink("Search", "Index", "Search", new { st = xxx }, null)
</div>
...
I also have a Search controller that needs to take a "st" value and looks like this
public class SearchController : Controller
{
// GET: Search
public ActionResult Index(string st)
{
ApplicationDbContext db = new ApplicationDbContext();
List<Report> filteredReports = db.Reports.Where(r => r.Tag == st).ToList();
return View(filteredReports);
}
}
What I'm not sure of how do is grab what ever value is selected from the drop down and add that to my Html.ActionLink where I just have 'xxx' now.
Clicking on the link usuallly does a new GET request to the href attribute value of the link. It will not send any data from your form.
You need to use javascript and hijack the click event on the link and append the selected option value from the SELECT element as querystring to that and send it.
So give an id to the link which you can use later to wireup the click event
#Html.ActionLink("Search", "Index", "Search", null, new {#id="search"})
And the javascript
$(function(){
$("#search").click(function(e){
e.preventDefault();
window.location.href=$(this).attr("href")+"?st="+$("#selection").val();
});
});
Another option is to use the form submit. Wrap your select element inside a form and have a submt button which sends the form to the action method. This method does not need javascript. But your select input element name should match with your parameter name.
#using(Html.BeginForm("Index","Search",FormMethod.Get))
{
<div>
Search
#Html.DropDownList("st", MyProject.Util.Lists.GetMyList(), "Select One")
<input type="submit" value="Search" />
</div>
}
If you do not prefer to have button, but need the link element, you can use javascript to submit the form (like we did in the first approach). With this approach you do not need to manually append the querystring.
You have to call a AJAX POST call to your controller which store selected value, and then when your action link event fire get stored value from there.
AJAX:
$.ajax(
{
url:your url,
data:{"st":dropdown selected value},
type:"post"
});
Controller:
public ActionResult Index()
{
string st=TempData["st"].ToString();
ApplicationDbContext db = new ApplicationDbContext();
List<Report> filteredReports = db.Reports.Where(r => r.Tag == st).ToList();
return View(filteredReports);
}
public void SetSt(string st)
{
TempData["st"] = st;
}

JqGrid - post data (with redirect) to controller action results in 404

I have a JqGrid with navigation extra button. In onClickButton event I want to post row data to another view, not only one value which could be done via action link. I need to be able to pass more variables with their values to perform parametric create action with prefilled values [for hidden inputs] and show in view. In this case I am sending only 2. JSON would more suitable. But let's continue.
.jqGrid('navButtonAdd', '#rolesPager',
{
caption: "",position: 'first',buttonicon: "ui-icon-plus",
title: $.jgrid.nav.addtitle,
onClickButton: function () {
$.post("/Administration/Roles/CreateWithParams", {
foreignColumn: 'WEB_USER_id', foreignValue: '1' }, function (data) {
location = "/Administration/Roles/CreateWithParams";
}).fail(function (error)
{
alert(error);
});
}});
Then I have a controller action:
//
// GET: /Administration/Roles/Create
[HttpGet]
[HttpPost]
public ActionResult CreateWithParams(string foreignColumn, int foreignValue)
{
ViewBag.WEB_ROLE_id = new SelectList(db.WEB_ROLE, "WEB_ROLE_id", "name");
ViewBag.WEB_USER_id = foreignValue;
return View();
}
Data are sent but rendering its view fails in 404 - Resource not found. In my post method I have only 2 parameters, but there can be sent as JSON - as just one variable passed to controller . I think that this has something to do with
location = "url";
statement where data are probably lost or changes something. I would need somehow find a way how to make the view of action CreateWithParams rendered (does not matter if GET or POST) with displaying of passed post values. For create action I do not need to pass model data, just previous values but called view wil use model. Every post action examples just returns callback but not display a controller action view using sent data. Or is this completely bad approach and it this is not possible? Or call another action from with resending data as result of CreateWithParams action? If it so could some point me to right direction?
It looks that ajax has its limitation and cannot be redirected with parameters easily. So hidden forms on a page must come to scene.
<form action="/Administration/Roles/CreateWithParams"
style="display: none" method="post"
name="roles_hiddenForm" id="#roles_hiddenForm"
novalidate="novalidate">
<input type="hidden" value="2" name="WEB_USER_id" id="WEB_USER_id">
<input type="hidden" value="WEB_USER_id" name="ForeignKeyColumn" id="ForeignKeyColumn">
<input type="hidden" value="2" name="ForeignKeyValue" id="ForeignKeyValue">
<input type="submit" name="roles_hiddenSubmit" id="roles_hiddenSubmit"></form>
and js I modified as:
.jqGrid('navButtonAdd', '#rolesPager',
{
caption: "",position: 'first',
buttonicon: "ui-icon-plus",
title: $.jgrid.nav.addtitle,
onClickButton: function () {
$("#roles_hiddenSubmit").click();
}
});

MVC - Need to pass data from View to Controller

I need to pass some information I have in a view to the controller.
When it goes to the controller, I like to then send out an email with that information.
I was thinking about using the #HTML.ActionLink the view but from my understanding, that goes to an ActionResult which I do not want as I want to be able to send out an email and not go back to the View.
Here is a way to do it with the post being done through jquery. There are other options but this was fresh in my mind since I just did it the other day.
HTML and javascript
#using (Html.BeginForm())
{
<input type="submit" value="SendEmail" onclick="SendEmail(); return false;" />
}
<script type="text/javascript">
function SendEmail() {
$.post('PathToController/SendEmail',
{
parameter: parameterValue
})
.success(function (result) {
// Display a message that the email was sent????
});
}
</script>
Controller
[HttpPost, ActionName("SendEmail")]
public string SendEmail(parameters)
{
}
You could also let the page handle the post as normal and not use the jquery. If this is the case, then your parameters would need to match the IDs of your controls you would need to use.

Search and display on same page in mvc2 asp net

have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it.
Right now I'm doing the following but it's not working out exactly the way I want:
sathishkumar,
You don't tag the question as being an ajax related solution or not. I'm going to present a simple ajax approach which may or may not be suitable.
in the controller:
public ActionResult Search(string searchTerm)
{
// you don't add code re your stored proc, so here is a repo based approach
var searchItems = _repository.Find(x => x.searchfield.Contains(searchTerm));
return PartialView("SearchPartial", searchItems);
}
main view (index.aspx or whatever) (below where your main content is defined, add):
<div id="searchResults"></div>
in another part of the page (semi psuedo-code):
<script type="text/javascript">
function getSearchResults() {
// #yoursearchbox is a textbox on the index.aspx aview
var tdata = { searchTerm: $('#yoursearchbox').val()};
// or your data in the format that will be used ??
$.ajax({
type: "GET",
data: tdata,
url : '<%= Url.Action("Search", "Home") %>',
success: function (result) { success(result); }
});
});
function success(result){
$("#searchResults").html(result);
}
</script>
You'd then add a partial view SearchPartial.ascx that contained your model for the search results.
Hope this helps.
You can use Ajax to solve the problem.
<div>
`#using (Ajax.BeginForm("action", "controller", new AjaxOptions
{
UpdateTargetId = "results",
HttpMethod = "GET",
}))
{
#Html.TextBox()
<input type="submit" value="Search" />
}`
<div id="results"></div>
</div>

Resources