Passing textbox value to ActionResult TempData in MVC5 - c#

I am very new to MVC , and trying to learn from videos given for MVC. In one of the video i have gone through the use of Tempdata. In the video they have shown created action result with HTTPPOST and pass data from textbox to controller and then to view using Tempdata . I have tried to practice the same . But i am not getting value from textbox,always returning as null. Below is my code,
Controller as below,
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(string name)
{
TempData["uname"] =name;
return RedirectToAction("GetUser");
}
public ActionResult GetUser()
{
return View();
}
View for Create as below,
#{
ViewBag.Title = "Create";
}
<h2>Create New User</h2>
#using (Html.BeginForm())
{
<div>
<p>Enter your name : <input type="text" id="id" placeholder="Enter username"/></p>
<p><input type="submit" id="btnSubmit" value="Create"/></p>
</div>
}
View for GetUser,
#{
ViewBag.Title = "GetUser";
}
<h2>GetUser</h2>
<div>
<h3>Welcome #TempData["uname"].ToString()</h3>
</div>
When i enter value in textbox and press button id parameter in Create action is null. Also i have not created any model class, as in video they have just shown as above code. Please give me some suggestions.
Regards
Sangeetha

if you are not using any model to send the data across , you should provide your textbox with a name attribute and that name attribute must match on the controller action , change your create view text box as shown
#using (Html.BeginForm())
{
<div>
<p>Enter your name : <input type="text" name="name" id="id" placeholder="Enter username"/></p>
<p><input type="submit" id="btnSubmit" value="Create"/></p>
</div>
}
I have added the name attribute to the text box

When you are passing values from view to controller by using input type=submit then you must set name attribute to the input elements,then you need to mention that name in method argument.
<input type="text" name="txtname" id="txtname" placeholder="Enter username"/>
<input type="submit" id="btnSubmit" value="Create"/>
Note : It will only work with input type="submit", it won't work with input type="button"
you don't need bind the Tempdata value with .ToString(). you can directly bind with #TempData["uname"]

Related

How to pass different data from 2 submit buttons in 1 form

I have 2 submit buttons in one form and I want to pass data from the button that is pressed to a the server and then server can set status based on the data given by form action.
I understand the C# part, I'm just not sure with what to do in Html to pass the data from the button to the form action
HTML
<form action="#Url.Action("Create", new{ name})" method="post">
<input type="submit" class="button" name="Draft" value="Save as draft " />
<input type="submit" class="button" name="Publish" value="Save and publish" />
<form>
C#
[HttpPost]
public async Task<IActionResult> Create(string name)
{
if (name== "Draft")
{
model.Status = IPublishable._Status.Draft;
}
else
{
model.Status = IPublishable._Status.Published;
}
}
Fastest and easiest way is to add a hidden field to your form and then add something to your submit function that gives it an appropriate value (like .js). Then you will need to process that field on your action page.
Instead of doing the dynamic thing,
Just want to inform you can check this as well it's a very simple and clean approach.
I've just created a sample code for you.
//Controller side code
public class TestController : ControllerBase
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string Name, string status)
{
return Json(status);
}
}
//View side code
<div>
<form asp-action="index" method="post">
<input type="text" name="Name" />
<button type="submit" class="button" name="status" value="1">
Save as draft
</button>
<button type="submit" class="button" name="status" value="2">
Save and publish
</button>
</form>
</div>
Here you can see the output
Just copy-paste the code to check yourself.
I have 2 submit buttons in one form and i want to pass data from the
button that is pressed to a the server and then server can set status
based on the data given by form action
Well, we can implement that using IFormCollection to handle any kind of dynamic request without defining the name and value in form. In fact, we can submit any kind of dynamic data to controller thus, we can retrive value as we posted there. You can do as following:
View:
<form action="Create" method="POST">
<input type="submit" class="button" name="Draft" value="Save as draft " />
<input type="submit" class="button" name="Publish" value="Save and publish"/>
</form>
Controller:
[HttpPost]
public async Task<IActionResult> Create(IFormCollection formData)
{
string? submittedButtonValue = formData.Keys.FirstOrDefault();
if (submittedButtonValue.Contains("Draft"))
{
model.Status = IPublishable._Status.Draft;
}
else if (submittedButtonValue.Contains("Publish"))
{
model.Status = IPublishable._Status.Published;
}
}
Note: Up to now, we can get all the data and value what we have submitted from the view.
Output:

Controller action method not being called making a post request in ASP.NET Core

I am trying to use model binding to send a file selected by the user to the controller, this action method is not being hit and I am not sure why. I put a breakpoint inside but it will not get hit.
Here is my import view:
#model FileModel
<h1 class="title-underline">Import file</h1>
<div class="form-group">
<form asp-controller="Import" asp-action="FileImport" method="POST" enctype="multipart/form-data">
<label for="importFile">Select a past grant to import</label>
<input type="file" id="importFile" name="importFile" asp-for="ImportFile">
</form>
<button type="submit" id="btnSubmit" class="btn btn-tnl btn-block">Import</button>
</div>
Here is my model:
public class FileModel
{
public IFormFile ImportFile { set; get; }
}
Here is my action method inside my ImportController:
[HttpPost, ValidateAntiForgeryToken]
public IActionResult FileImport(FileModel model)
{
IFormFile file = model.ImportFile;
var fileName = Path.GetFileName(file.FileName);
var contentType = file.ContentType;
return View("Index");
}
I have provided the controller, action, method, and enctype so I'm not sure what else is missing which is stopping the method from being hit. Is it something to do with the model in the parameter?
One problem that I see is the submit button is outside of the form. It is not doing anything when you click it. Try bringing it into the <form>...</form> block and make the input type = "submit", not "button". Or write a click handler for it that would call submit on the form.
You can check the syntax here
https://www.w3schools.com/html/html_form_elements.asp
<div class="form-group">
<form asp-controller="Import" asp-action="FileImport" method="POST" enctype="multipart/form-data">
<label for="importFile">Select a past grant to import</label>
<input type="file" id="importFile" name="importFile" asp-for="ImportFile">
<input type="submit" id="btnSubmit" class="btn btn-tnl btn-block" value="Import">
</form>
</div>
Your button should be inside form tag. Not outside.
<form>
<button type="submit">Import</button>
</form>

Send string from View to Controller using httpGet - MVC

I am new to MVC so please bear with me.
I am trying to send a string from a textbox to a controller method so I can find an object in a database. However, I do not know how to send the string successfully from the view to the controller in a HttpGet request (only in HttpPost)
The code in my view
<div>
<label>Email</label>
#Html.TextBox("email")
</div>
<div class="btn btn-success">
#Html.ActionLink("Edit RSVP", "Edit")
</div>
The ViewResult method in my controller
// Problem is the email parameter is always null
[HttpGet]
public ViewResult Edit(string email)
{
// If the email the typed is find, it will display their contents on to a RsvpForm view
return View("RsvpForm", guestRepository.Find(email));
}
Anyone know how I can send this string through, I would be grateful.
Thanks
Like this:
#using (Html.BeginForm("Edit", "ControllerName", FormMethod.Get))
{
<div>
<label>Email</label>
#Html.TextBox("email")
</div>
<div class="btn btn-success">
<input type="submit" value="Edit RSVP" />
</div>
}
Note: I can't tell from your description whether or not you are trying to do this without reloading the page. This option will post the page to the controller, so you will get a page reload.
If you want this to load without posting the page, you can look into Ajax.BeginForm. Here is a StackOverflow article with a decent primer on the AJAX form.
update
For your example, you may could do something like this if you want to use AJAX. This is all untested, but may be close to what you would need.
First you can create a partial view that represents the user data that you want to display:
RsvpForm.cshtml
#model GuestData
<div class="hdr">Name</div>
<div class="value">#Model.Name</div>
<div class="hdr">Email</div>
<div class="value">#Model.Email</div>
Then you want to make sure that your controller returns the partial view based on the email that is sent via the GET:
GuestDataController.cs
[HttpGet]
public ActionResult Edit(string email)
{
// If the email the typed is find, it will display their contents on to a RsvpForm view
return PartialView("RsvpForm", guestRepository.Find(email));
}
Then you create the AJAX form to submit the request via a GET and load the partial view without reloading the page: view.cshtml
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("Edit", "GuestData", null, new AjaxOptions { UpdateTargetId = "UserData", HttpMethod = "Get" }, null))
{
<div>
<label>Email</label>
#Html.TextBox("email")
</div>
<div class="btn btn-success">
<input type="submit" value="Edit RSVP" />
</div>
}
<div id="UserData"></div>
The easiest way to do it is to create a form as follow :
#using(Html.BeginForm("Edit", ControllerName, FormMethod.GET))
{
#Html.Label("Email")
#Html.TextBox("email")
<input type="submit" value="Edit RSVP"/>
}
or you can use Jquery to change the link when textbox value change (which I do not recommend):
$('input[name=email]').on('change' function()
{
var value = $(this).val();
var href = $('.btn').next('a').attr('href');
href += '?email='+value;
$('.btn').next('a').attr('href', href)
});

How to use textbox and ViewBag value in controller method?

#using (Html.BeginForm("sendcode", "Home", FormMethod.Post))
{
<div class="selected">You Selected:</div>
<div class="sname">#ViewBag.selectsong</div>
<div class="enter" style="width:458px;height:37px; text-align:left;">
<div class="selected">Enter your mobile number</div>
<div class="mobileno">
<div><div class="spann">+91</div><input name="MNumber" type="text" class="mobileinput"/></div></div>`enter code here`
<div class="confirm"><input name="" type="button" class="confirmb"value="Confirm"onclick="location.href='#Url.Action("getdetail", "Home" )'/>
</div>
<div class="applicablee">* charges applicable as per your mobile operators</div>
</div>
}
I want to use textbox value and ViewBag value on my controller method which has been defined below?
public string getdetail(string Mnumber, string sSongName)
{
string ss = Mnumber;
string ss1 = sSongName;
return ss;
}
viewbag is a one way property
if you want to return it value you must define your variable as a property of your model
then pass the model as a parameter to your action
If you want to fill your textbox with ViewBag value try this;
<input type="textbox" id="aa" name="aa" value="#Viewbag.X"/>
If you want to pass that value use hidden method Satpal mentioned about.

How to send text from the textbox to the actionResult?

I have a question about MVC4 (Razor). I have page where I want to filter data. There is a textbox (input) and a submit button. I want to move the text in the textbox to the actionresult. How can I resolve this?
On my page I've the following row:
#{ using (Html.BeginForm("Experiences"))
{
<span class="label">Filter on:</span><input id="FilterText" type="text" size="50"/>
<input type="submit" value="Submit" name="knowledge" /><br />
}
}
<br />
And I want to call the ActionResult Experiences
public ActionResult Experiences(string knowledge = "")
{
ReadExperienceData(knowledge);
return View(ListOfExperiences);
}
Specify the name property value of the input element same as the action method parameter name.
<input id="FilterText" name="knowledge " type="text" size="50"/>
<input type="submit" value="Submit" name="submitKnowledge" />
Also it looks like you are not using the Beginform method properly. You may try any of the below overloads, as needed
#using(Html.Beginform("Knowledge","YourControllerName"))
{
//form elements
}
or
#using(Html.Beginform())
{
//form elements
}

Categories