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
}
Related
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:
I have a .cshtml view like this:
<form asp-controller="X" asp-action="Y">
#for (int i = 0; i < Model.SomeListOfStrings.Count; i++)
{
<input type="checkbox" value="#Model.SomeListOfStrings[i]" />
}
<input type="submit" />
</form>
I want to send the value of this <input type="checkbox" value="#Model.SomeListOfStrings[i]" /> instead of the boolean in my request (and only if the checkbox is checked). How can I do this?
You should be able to do something like this in your cshtml:
<form asp-controller="Home" asp-action="Index">
#for (int i = 0; i < Model.SomeListOfStrings.Count; i++)
{
<input name="AreChecked" type="checkbox" value="#Model.SomeListOfStrings[i]" /> #Model.SomeListOfStrings[i]
<br />
}
<input type="submit" />
</form>
Give your input's the same name - AreChecked in this example. Set the value to your strings in your collection as you are already.
Then, in your controller method, add a List<string> parameter called AreChecked or whatever you named it, and that should automatically bind the checked items and have their values upon submitting:
[HttpPost]
public IActionResult Index(List<string> AreChecked)
{
return Ok();
}
Example view:
If I check the "hi" and "hello" checkboxes, when I submit the form, the controller's parameter is bound with those values:
I referenced this page to do this if you want more information.
I have tried the below but I get the compliation error:
The name 'txtMakeModelTypeCode' does not exist in the current context.
<label>Type Code</label>
<input type="text" id="txtMakeModelTypeCode" name="txtMakeModelTypeCode" />
<label>Make</label>
<input type="text" id="txtMake" name="txtMake"/>
<label>Model</label>
<input type="text" id="txtModel" name="txtModel"/>
Create
I have also tried using a form but I don't want to use a submit button. Is it possible to use a plain button?
#using (Html.BeginForm("CreateMakeModel", "Vehicle"))
{
<label>Type Code</label>
#Html.TextBox("txtMakeModelTypeCode")
<label>Make</label>
#Html.TextBox("txtMake")
<label>Model</label>
#Html.TextBox("txtModel")
<input type="submit" value="Create" />
}
MVC does not work the same as ASP.Net Webforms. The textboxes you create are not available in code. You use the controls to render your html and handling of data is done via the model.
So use TextBoxFor:
#using (Html.BeginForm("CreateMakeModel", "Vehicle"))
{
<label>Type Code</label>
#Html.TextBoxFor(m => m.MakeModelTypeCode)
<label>Make</label>
#Html.TextBoxFor(m => m.Make)
<label>Model</label>
#Html.TextBoxFor(m => m.Model)
<input type="submit" value="Create" />
}
Then in your controller, after the post, you should have the posted data in the model:
public ActionResult Index(CreateMakeModel model) // or is it Vehicle?
{
// whatever you do here:
string code = model.MakeModelTypeCode;
}
I am thinking of having something like this:
#if(Model.ShowSubmitButton)
{
<input id="submitButton" type="submit" value="Update stuff" />
}
else
{
<input id="continueButton" type="submit" value="Continue to next page" />
}
Then in controller is it possible to know which button it is getting called from?
I originally had my controller method working with the first button, now adding a second button with different functionality, wanted to see if using the same method I can determine which button was clicked ? and if it is not possible this way, then what do you suggest?
Not without extra information. I would likely split them up rather than have two submit buttons for the same form doing two different things but if you really want to go down that road one way would be to add an additional posted variable that tells you which was clicked.
#if(Model.ShowSubmitButton)
{
<input type="hidden" name="submitStyle" value="update"/>
<input id="submitButton" type="submit" value="Update stuff" />
}
else
{
<input type="hidden" name="submitStyle" value="continue"/>
<input id="continueButton" type="submit" value="Continue to next page" />
}
To answer your additional question. Either you can add this variable to your model posted back or add it as an additional parameter.
// Where "MyModel" has a public property "SubmitStyle"
public ActionResult MyAction(MyModel model)
// Or an int, string, whatever type of parameter you want/need.
// In my example it was a string so...
public ActionResult MyAction(string submitStyle/*, <other params...>*/)
You could add a hidden field. Not ideal solution, but does the job.
#if(Model.ShowSubmitButton)
{
<input type="hidden" name="buttonClicked" value="1">
<input id="submitButton" type="submit" value="Update stuff" />
}
else
{
<input type="hidden" name="buttonClicked" value="2">
<input id="continueButton" type="submit" value="Continue to next page" />
}
In your controller you would accept it as:
public ActionResult MyAction(MyObject myobj, int buttonClicked)
There is an elegant way (tested only on chrome yet), define two inputs
<input type="submit" value="Next" name="Action"/>
<input type="submit" value="Prev" name="Action"/>
Now in you input model in controller put model defined like this:
public class MyModelDto
{
// other properties
public MyCustomAction Action { get; set; }
}
Where the
public enum MyCustomAction
{
Next=0,
Prev=1
}
Now check the value of action.
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"]