MVC - Need to pass data from View to Controller - asp.net-mvc

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.

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()

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();
}
});

Can you just update a partial view instead of full page post?

Is there a way to submit a partial view form in asp.net mvc without reloading the parent page, but reloading the partial view only to its new state? Similar to how knockout.js updates using data-bind.
My data table renders with a variable number of columns/names so I don't think knockout.js is an option for this one, so I am trying to use a partial view instead.
Not without jQuery.
What you would have to do is put your Partial in a div, something like:
<div id="partial">
#Html.Partial("YourPartial")
</div>
Then, to update (for example clicking a button with the id button), you could do:
$("#button").click(function () {
$.ajax({
url: "YourController/GetData",
type: "get",
data: $("form").serialize(), //if you need to post Model data, use this
success: function (result) {
$("#partial").html(result);
}
});
})
Then your action would look something like:
public ActionResult GetData(YourModel model) //that's if you need the model
{
//do whatever
return View(model);
}
Actually, if your Partial has a child action method, you can post (or even use an anchor link) directly to the child action and get an Ajax-like affect. We do this in several Views.
The syntax is
#Html.Action("MyPartial")
The Child Action is
public ActionResult MyPartial()
{
return PartialView(Model);
}
If your form posts to the child action
#using (Html.BeginForm("MyPartial"))
{
    ...
}
The Partial View will be updated with the partial view returned from the child action.
Jquery is still a legitimate way to update a partial. But technically, the answer to your question is YES.
As normal what I find when looking for things like this is people give too limited information so I will attempt to help here. The key is to set up a div with an ID you can append the return html to. Also when hitting your controller make sure it returns the partial. There are some potential problems with this method but on a good day it should work.
<div id="CategoryList" class="widget">
#{
Html.RenderPartial("WidgetCategories.cshtml");
}
</div>
function DeleteCategory(CategoryID) {
$.get('/Dashboard/DeleteWidgetCategory?CategoryID=' + CategoryID,
function (data) {
if (data == "No") {
alert('The Category has report widgets assigned to it and cannot be deleted.');
}
else {
$('#CategoryList').html(data);
}
}
);
}
[HttpGet("DeleteWidgetCategory")]
[HttpPost("DeleteWidgetCategory")]
public IActionResult DeleteWidgetCategory(string CategoryID)
{
string Deleted = CategoryModel.DeleteCategory(CategoryID);
if (Deleted == "Yes")
{
return PartialView("WidgetCategories");
}
else
{
return this.Json("No");
}
}
I would use the Ajax Form helper for such scenarios using a partial view and #html.RenderPartial("partialName")
partial helpers
In your Main View
<div id=SearchResult>
#Html.Partial("_NameOfPartialView", Model)
</div>
<input type="button" id="btnSubmit" value="Submit">
In your Javascript file
$('#btnSubmit').click(function () {
GetData(Id);
});
function GetData(Id){
$.ajax({
url: "/Home/GetEmployee/",
type: "get",
data: { Id:Id },
success: function (result) {
$('#SearchResult').html(result);
}
});
}
In your Home Controller
public ActionResult GetEmployee(int Id)
{
var employee= context.Employee.Where(x=> x.EmployeeId == Id)
return this.PartialView("_NameOfPartialView", employee);
}

How to Hide Parameters of URL in MVC4

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());

how to render a full view using Ajax.BeginForm

I have a partial view which has a Ajax.BeginForm, with a UpdateTargetID set. When the validation on the form fails the update target id is replaced with the validation errors, but when there are no validation errors users should be redirected to a new page.
The code in my Partial view is
<div id="div_UID">
<% using (Ajax.BeginForm("FindChildByUID", new AjaxOptions { UpdateTargetId = "div_UID" } ))
{%>
<p>
<label>UID:</label>
<%= Html.TextBox("UID") %>
</p>
<input type="submit" value="Continue" />
<% } %>
</div>
</pre>
The code in my controller is as follows
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FindChildByUID(Student student)
{
Student matchingStudent = _studentService.FindChildByUID(student.UID);
if (matchingStudent == null)
{
ModelState.AddModelError("UID", String.Format("No matching child found for the entered UID: {0}", student.UID));
return PartialView();
}
else
{
// full view
return RedirectToAction("ConfirmChildDetails", matchingStudent);
}
}
So, for I have been unsuccessful to display the full view on it's own, as it always seems to dipslay the full view in the UpdateTargetID div specfied in the Ajax.BeginForm.
Any suggestions on how I can get this to work?
Thanks
What your AJAX post is doing is making a request and waiting on a response that contains html to input onto the page. The configuration is such that whatever html is returned will be injected into the div you've named "div_UID".
I typically avoid scenarios like this and use traditional posting if a redirect is required upon a successful outcome of the POST.
I imagine you could do it like this using jQuery to submit rather than the Ajax.BeginForm (or just set a callback function for your Ajax.BeginForm):
function SubmitForm(form) {
$(form).ajaxSubmit({ target: "#div_to_update", success: CheckValidity });
}
function CheckValidity(responseText) {
var value = $("#did_process_succeed").val();
if (value == "True") {
window.location.replace("url_of_new_action_here");
}
}
You just have to have a hidden field in your partial view called "did_process_succeed" and set the value of True or False based on some logic in your controller.
There are likely other ways as well. Perhaps someone else will chime in. I hope this helps for now.

Resources