I have problem with passing values by POST in ASP.NET MVC 4
This is my action in User controller:
[HttpPost]
public string Show(int? uid, string uname)
{
return uname + uid.ToString();
}
And this is how I tried to pass values in view:
#using (Html.BeginForm("Show", "User"))
{
Html.Hidden("uid", Model.Id);
Html.Hidden("uname", Model.UserName);
<input type="submit" value="+"/>
}
html:
<form action="/User/Show" method="post"> <input type="submit" value="+"/> </form>
and:
#using(Html.BeginForm("Show", "User", FormMethod.Post, new { uid = 1, uname = "user1" }))
{
<input type="submit" value="+"/>
}
html:
<form action="/User/Show" method="post" uid="1" uname="user1"> <input type="submit" value="+"/></form>
In both ways Show action receives null instead real values.
Your HtmlHelpers are not being rendered. Use Razor syntax.
#using (Html.BeginForm("Show", "User"))
{
#Html.Hidden("uid", Model.Id);
#Html.Hidden("uname", Model.UserName);
<input type="submit" value="+"/>
}
Explanation:
Calling Html.Hidden (or Html.[anything]) is a method and usually returns an IHtmlString. Without using # infront, the engine doesn't know that you're trying to output the returned string. It just thinks you're calling a method.
This is not a good approach for an action that receives data. This approach can offer many security breaches, like data injection., essentially lots of fields.
The right thing is create a Model (or a ViewModel, if you don't want to persist the data) to make the correct guidance between View and Controller:
ViewModel:
public class MyViewModel {
public int? uid { get; set; }
public string uname { get; set; }
}
View:
#model MyProject.ViewModels.MyViewModel
#using (Html.BeginForm("Show", "User"))
{
Html.HiddenFor(model => model.uid);
Html.HiddenFor(model => model.uname);
<input type="submit" value="+"/>
}
Controller:
public ActionResult Show(int modelId) {
var model = context.Model.SingleOrDefault(m => m.ModelId == modelId);
var viewModel = new MyViewModel();
viewModel.uid = model.Id;
viewModel.uname = model.UserName;
return View(viewModel);
}
[HttpPost]
public string Show(MyViewModel viewModel)
{
return viewMode.uname + viewModel.uid.ToString();
}
You're not actually creating hidden fields in your form. You need the # in front of you Hidden helper, and drop the semi-colon at the end.
#using (Html.BeginForm("Show", "User"))
{
#Html.Hidden("uid", Model.Id)
#Html.Hidden("uname", Model.UserName)
<input type="submit" value="+"/>
}
The reason your hard-coded test didn't work is that your HTML wasn't correct. You can't just put the values you want to post on the <form> element, you need to have them as hidden fields in the form.
<form action="/User/Show" method="post">
<input type="hidden" name="uid" value="1" />
<input type="hidden" name="uname" value="user1">
<input type="submit" value="+"/>
</form>
It would be better if you could use a view model.
public class MyViewModel
{
public int? Id {get;set;}
public string UserName {get;set;}
}
public ActionResult Show()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Show(MyViewModel model)
{
return Content(string.format("{0} - {1}", model.Id, model.UserName));
}
(Coded in notepad so untested, but should work.)
Related
How can do I set the default value to a hidden input box in html page using ASP.NET MVC.
Seems you are trying to set hidden value on asp.net MVC. You could
try below way.
Model:
public class HiddenValueModel
{
public int HiddenValueId { get; set; }
public String HiddenValueName{ get; set; }
}
Load Default View From Controller:
public IActionResult HiddenValueExample()
{
return View();
}
View:
#model MVCApps.Models.HiddenValueModel
#{ ViewBag.Title = " "; }
<h2>Hidden Value Example </h2>
<hr />
#using (Html.BeginForm("HiddenValueExamplePost", "controllerName"))
{
<table class="table table-sm table-bordered table-striped">
<tr><th>HiddenValueName </th><td id="HiddenValueName"> #Html.TextBoxFor(r => Model.HiddenValueName, new { #class = "form-control" })</td></tr>
<tr><th>HiddenValue Id Which Is Hidden</th><td id="HiddenValueId"><input type="hidden" id="HiddenValueId" name="HiddenValueId" value="01052022" /></tr>
</table>
<input id="Button" type="submit" value="Save" class="btn btn-primary" style="margin-left:1091px" />
}
Note: Here you could see HiddenValueId we have set the value into the feild and keep that hidden. But when you would submitted the
value to the controller it would be there. Additionally, if you want to bind the hidden value from your backend you can use this way #Html.HiddenFor(m => m.HiddenValueId, new { #value = Model.HiddenValueId} ). You could also have a
look more details on official document here
Submit Value To Controller:
[HttpPost]
public IActionResult HiddenValueExamplePost(HiddenValueModel modelWithHiddenValue)
{
return View();
}
Output:
When Bind From Controller:
public IActionResult HiddenValueExample()
{
var hiddenExamVal = new HiddenValueModel();
hiddenExamVal.HiddenValueId = 10101;
hiddenExamVal.HiddenValueName = "Test Hidden Value";
return View(hiddenExamVal);
}
Bind From Controller and submit that value again to controller:
In this case update the view like this :
#model MVCApps.Models.HiddenValueModel
#{ ViewBag.Title = " "; }
<h2>Hidden Value Example </h2>
<hr />
#using (Html.BeginForm("HiddenValueExamplePost", "StackOverFlow"))
{
<table class="table table-sm table-bordered table-striped">
<tr><th>HiddenValueName </th><td id="HiddenValueName"> #Html.TextBoxFor(r => Model.HiddenValueName, new { #class = "form-control" })</td></tr>
<tr><th>HiddenValue Id Which Is Hidden</th><td id="HiddenValueId">#Html.HiddenFor(m => m.HiddenValueId, new { #value = Model.HiddenValueId} )<br /></tr>
</table>
<input id="Button" type="submit" value="Save" class="btn btn-primary" style="margin-left:1091px" />
}
<br />
Output Using Backend Binding:
Hope it would guided you accordingly.
Creating a Hidden Field in ASP .NET MVC
Studentmodel:
public class Student{
public int StudentId { get; set; }
public string StudentName { get; set; }}
HiddenFor() in Razor View:
#model Student
#Html.HiddenFor(m => m.StudentId)
Html Result :
<input data-val="true"
data-val-number="The field StudentId must be a number."
data-val-required="The StudentId field is required."
id="StudentId"
name="StudentId"
type="hidden"
value="" />
Html.Hidden() :
#model Student
#Html.Hidden("StudentId")
Html Result :
<input id="StudentId" name="StudentId" type="hidden" value="1" />
Basic Helper (#Html.Hidden())
If you want a Hidden Field with its value set you can try this:
#Html.Hidden("Jeremy", "Thompson")
The Hidden Field's name will be "Jeremy", and the value of the Hidden Field will be "Thompson".
Strongly Typed Helper (#Html.HiddenFor()) / Model Binding
The strongly typed helper contains 2 parameters:
Hidden Field name which is the name of a Model Property.
Value of Hidden Field (if we want to set the value from the view).
Declaration of Hidden Field using strongly typed helper:
#Html.HiddenFor(m => m.StudentID, new { Value = "1" })
Ref
In my project I would like to pass more than one parameter (id and description) to my view from the controller.
This is the structure of my project:
ProductController:
public IActionResult DettaglioDescrizione(int id, string descrizione)
{
ViewData["ProductId"] = id;
ViewData["ProductDescription"] = descrizione;
return View("Details");
}
Details.cshtml view:
<div class="text-center">
<h1 class="display-4">Prodotti</h1>
<p>Id prodotto: #ViewData["ProductId"]</p>
<p>Descrizione prodotto: #ViewData["ProductDescription"]</p>
</div>
I know that I have to modify my pattern in Startup.cs. If I modify in this way it works properly:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}/{descrizione?}");
});
My question is: there is a better way to do this without add "/" for each parameter?
There are three binding sources in model binding
Form Values
Route Values
Query string
what you are doing right now is from a route value, maybe you can use a query string /1?description=value or maybe you can do httppost and get the value from the form.
If you want to pass multiple parameters from controller to action or from action to controller.You can try to create a Model.Action can pass data with a form to controller.Action returns a model to view.So that you don't need to pass more than one parameters with route or ViewData.Here is a demo:
Model:
public class Product
{
public int ProductId { get; set; }
public string descrizione { get; set; }
}
Action:
public IActionResult DettaglioDescrizione(Product product)
{
return View("Details",product);
}
Details View:
#model Product
<div class="text-center">
<h1 class="display-4">Prodotti</h1>
<p>Id prodotto: #Model.ProductId</p>
<p>Descrizione prodotto: #Model.ProductDescription</p>
</div>
View:
#model Product
<form method="post" asp-action="DettaglioDescrizione">
<div class="form-group">
<label asp-for="ProductId" class="control-label"></label>
<input asp-for="ProductId" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ProductDescription" class="control-label"></label>
<input asp-for="ProductDescription" class="form-control" />
</div>
<input type="submit" value="submit" />
</form>
result:
Im working on html content to disply data in mvc view binding data from model class, my requirement is to set values to input fields to html content from c#.
i want final content should come up with html content and values from model.
EXAMPLE:
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>
This is my html content which is coming from text file. i've data in my model, i.e,
public class EmployeeModel
{
public string fname { get; set; } = "Stack";
public string lname { get; set; } = "OverFlow";
}
In View :
#Html.Raw(ViewBag.htmlContent)
This is what the HtmlHelper class is for.
Set the view model in your view file and create a form around it.
#model Models.EmployeeModel
#using (Html.BeginForm("Edit", "Employees", FormMethod.Post))
{
#Html.LabelFor(m => m.fname)
#Html.TextBoxFor(m => m.fname)
<input type="submit" value="Submit"/>
}
Invoke the view from your controller with an instance of the model to edit.
public IActionResult Edit(int id)
{
...
employee = service.GetEmployeeById(id);
return View(employee);
}
one thig you could try would be to set values in Razor:
// your controller
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new EmployeeModel());// pass the actual viewmodel instance to the view here
}
}
#model EmployeeModel
.......
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" value="#Model.fname"><br><br> <!-- reference #Model fields as usual -->
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" value="#Model.lname"><br><br><!-- reference #Model fields as usual -->
<input type="submit" value="Submit">
</form>
and a fiddle for you to play with: https://dotnetfiddle.net/37asAw
In my controller I have the following code:
public ActionResult Index(int? videoId, int languageId = 0)
{
//Some code
}
Then in my .chtml page I reference it like so:
#using (Html.BeginForm("Index", "VideoLanguage", FormMethod.Post))
{
#Html.Hidden("videoId", Model.VideoId)
#Html.Hidden("videoLanguageId", Model.SelectedLanguage.LanguageId)
<div>
#Html.DropDownListFor(model => model.SelectedLanguage.LanguageId, ViewData["LanguageId"] as SelectList)
</div>
<div>
Add Language
</div>
... code keeps going
So what happens when i click the button, the selected value for LanguageId from the drop down isnt passed. The original value is.
Add Language
Is set when the page loads, so the values in the HTML will be hardcoded in. What you need to do is either set the hyperlink parameters in Javascript OR use:
<input type="submit" value="Index" />
See How to pass a textbox value from view to a controller in MVC 4?
try this:
#using (Html.BeginForm("Index", "VideoLanguage", FormMethod.Post, new { videoId = Model.VideoId, languageId = Model.SelectedLanguage.LanguageId }))
{
....
}
You should pass your params to the #Html.BeginForm helper and just submit the form
#using (Html.BeginForm("Index", "VideoLanguage", FormMethod.Post, new { videoId = Model.VideoId, languageId = Model.SelectedLanguage.LanguageId }))
{
#Html.Hidden("videoId", Model.VideoId)
#Html.Hidden("videoLanguageId", Model.SelectedLanguage.LanguageId)
<div>
#Html.DropDownListFor(model => model.SelectedLanguage.LanguageId, ViewData["LanguageId"] as SelectList)
</div>
<div>
<input type="submit" value="Add Language"/>
</div>
... code keeps going
}
in your Controller you also should have two methods GET and SET with the same name:
public ActionResult Index()
{
//Here just get a view
}
[HttpPost]
public ActionResult Index(int? videoId, int languageId = 0)
{
//Here code to save in database
}
I just started studying MVC few days back. As far as I know, I did a small sample program. But some doubts I been facing. I am posting my doubts and code below. Please help me to understand it clearly.
Here I created four views and controller and a student class.
StudentClass
public class Student
{
public string Name { get; set; }
public string Age { get; set; }
public string Place { get; set; }
}
ViewOne
#model MyTestMVCApp.Models.Student
#{
ViewBag.Title = "ViewOne";
}
#using (Html.BeginForm())
{
<table style="border-color:Black;">
<tr>
<td>Name</td><td>Age</td><td>Place</td>
</tr>
<tr>
<td>--</td><td>--</td><td>--</td>
</tr>
</table>
<label>Enter Name : </label>
#Html.TextBoxFor(model => model.Name, new { name = "name"});
<input name="submit" type="submit" id="btnStart" class="button" value="Start Filling Details" />
ViewTwo.cshtml
#model MyTestMVCApp.Models.Student
#{
ViewBag.Title = "ViewTwo";
}
#using (Html.BeginForm())
{
<table style="border-color:Black;">
<tr>
<td>Name</td><td>Age</td><td>Place</td></tr>
<tr>
<td>#Model.Name</td><td>#Model.Age</td><td>#Model.Place</td>
</tr>
</table>
<label>Enter Age : </label>
#Html.TextBoxFor(model => model.Age, new { name = "age" });
<input name="submit" type="submit" id="btnNext" class="button" value="Next" />
}
ViewThree.cshtml
#model MyTestMVCApp.Models.Student
#{
ViewBag.Title = "ViewThree";
}
#using (Html.BeginForm())
{
<table style="border-color:Black;">
<tr><td>Name</td><td>Age</td><td>Place</td></tr>
<tr><td>#Model.Name</td><td>#Model.Age</td><td>#Model.Place</td></tr>
</table>
<label>Enter Age : </label>
#Html.TextBoxFor(model => model.Place, new { name = "place" });
<input name="submit" type="submit" id="btnNext" class="button" value="Next" />
}
ViewFour.cshtml
#model MyTestMVCApp.Models.Student
#{
ViewBag.Title = "ViewFour";
}
#{
<table style="border-color:Black;">
<tr><td>Name</td><td>Age</td><td>Place</td></tr>
<tr><td>#Model.Name</td><td>#Model.Age</td><td>#Model.Place</td></tr>
</table>
}
MyViewController.cs
public class MyViewController : Controller
{
public ActionResult ViewOne()
{
Student student = new Student();
return View(student);
}
[HttpPost]
public ActionResult ViewOne(Student student)
{
return View("ViewTwo", student);
//return RedirectToAction("ViewTwo",student);
}
[HttpPost]
public ActionResult ViewTwo(Student student)
{
return View("ViewThree", student);
//return RedirectToAction("ViewThree", student);
}
[HttpPost]
public ActionResult ViewThree(Student student)
{
return View("ViewFour", student);
}
}
My doubts
doubt 1. On the button click in ViewTwo,
[HttpPost]
public ActionResult ViewOne(Student student)
{
}
is debugging instead of ViewTwo's [HttpPost] actionresult.. Why ?
doubt 2. How can I pass the same instance of the student object I created in the ViewOne to all other Views , because my need is
On ViewOne, I get 'name' property of the student, then I pass the same object to ViewTwo.
On ViewTwo, I get 'age' property of the student, then I pass the same object to ViewThree.
On ViewThree, I get 'place' property of the student, then I pass the same object to ViewFour.
On ViewFour I display all the values of the student that I get through the above views.
It looks like you are returning ViewTwo from ViewOne's post action. When you do that you're still routing to the ViewOne action. The code below will show in your address bar as ViewOne, even though you're returning ViewTwo. Looks like you had the right idea at some point where you had a RedirectToAction call but you don't have an HttpGet for the ViewTwo action.
[HttpPost]
public ActionResult ViewOne(Student student)
{
return View("ViewTwo", student);
//return RedirectToAction("ViewTwo",student);
}
Another option, and this would probably be useful for you since you're trying to pass your Student object, would be to use RedirectToRoute where you pass the Student name, id or some other identifying item, as a parameter in the route. So the uri would end up looking something like this: ../MyView/ViewTwo/Joe
Because you are calling from ViewOne. if you want execute ViewTwo Action then use as below
#using (Html.BeginForm("ViewTwo", "MyView", FormMethod.Post))
It looks like it is the view definition that you have missed a small bit of logic.
the reason why you are hitting ViewOne on postback is because you are not setting the values the form it posting back to.
so in your ViewOne.cshtml and subsequent views you would need
#Html.BeginForm("ViewTwo","MyViewController")
{
//View code
}
The HTML.BeginForm will render with the RouteData if you do not provide it in the call for begin form.