How to access hiddenField value in asp.net mvc postback controller action? - asp.net-mvc

Can we access the asp:Label value directly in an MVC postback controller action? I would also like to know how to access the hiddenField value in an ASP.NET MVC postback controller action.

In ASP.NET MVC, you don't use <asp:... tags, but you could try POSTing any number of inputs within a form to a controller action where a CustomViewModel class could bind to the data and let you manipulate it further.
public class CustomViewModel
{
public string textbox1 { get; set; }
public int textbox2 { get; set; }
public string hidden1 { get; set; }
}
For example, if you were using Razor syntax in MVC 3, your View could look like:
#using (Html.BeginForm())
{
Name:
<input type="text" name="textbox1" />
Age:
<input type="text" name="textbox2" />
<input type="hidden" name="hidden1" value="hidden text" />
<input type="submit" value="Submit" />
}
Then in your controller action which automagically binds this data to your ViewModel class, let's say it's called Save, could look like:
[HttpPost]
public ActionResult Save(CustomViewModel vm)
{
string name = vm.textbox1;
int age = vm.textbox2;
string hiddenText = vm.hidden1;
// do something useful with this data
return View("ModelSaved");
}

In ASP.NET MVC server side controls such as asp:Label should never be used because they rely on ViewState and PostBack which are notions that no longer exist in ASP.NET MVC. So you could use HTML helpers to generate input fields. For example:
<% using (Html.BeginForm()) { %>
<%= Html.LabelFor(x => x.Foo)
<%= Html.HiddenFor(x => x.Foo)
<input type="submit" value="OK" />
<% } %>
and have a controller action which would receive the post:
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
// model.Foo will contain the hidden field value here
...
}

Related

Update a field in view based on the model in ASP.NET MVC

I need to do a calculator in ASP.NET MVC.
For the beginning I want to receive the value from the input field in controller and prefix it with the string "123". At the end I will process the expresion received and return the result.
I have the following model:
namespace CalculatorCloud.Models {
public class Calculator
{
public string nr { get; set; }
} }
In the view I am using the model:
#model CalculatorCloud.Models.Calculator
#{
ViewBag.Title = "Calculator";
}
#using (Html.BeginForm("Index", "Home"))
{
<div>
<div class="header">
#Html.TextBoxFor(m => m.nr, new { #id = "nr"})
<input type="button" id="C" name="C" value="C" />
<input type="button" id="back" name="back" value="<-" />
[...]
<div class="sum">
<input type="submit" value="=" />
</div>
</div>
}
The controller is like this:
namespace CalculatorCloud.Controllers
{
public class HomeController : Controller
{
Calculator model = new Calculator();
public ActionResult Index(string nr)
{
model.nr = "123" + nr;
return View(model);
}
}
}
I have the following problem: when pressing on submit button I am expecting to be displayed on the textbox the value from that was previously in the textbox, prefixed with the string "123".
But now it is kept the value from the textbox without the string "123".
Can someone help me with this?
Thank you! :)
If you want to modify the value of a model property in a postback action you will need to remove it from the ModelState:
public ActionResult Index(string nr)
{
ModelState.Remove("nr");
model.nr = "123" + nr;
return View(model);
}
The reason for this is that Html helpers such as TextBoxFor will first look at the value present in the ModelState and then in your view model property when rendering the value. This is by design.

MVC - How to simply do something at button click?

I am new to ASP.NET MVC. I was used to program using just ASP.NET. I want to do something when the user clicks a button. I am not understanding what do I do at Controller.
I have this View:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Action("RegisterHour", "Register")
and the Controller:
public ActionResult RegisterHour()
{
//TODO: do anything
return View("Index");
}
When I click at the button, I would like to stay in the same page (it can reload). I simply want to do something like go to the database and create a new entity, and then show a messagebox.
This code causes an stackoverflow. What am I missing? What do I have to change at Controller?
Thanks.
The line
#Html.Action("RegisterHour", "Register")
actually makes a request to the server in order to render the result of the "RegisterHour" action. So in order to render the result of the action the first time, you need to make a request to the same action. This causes an endless loop, hence the stack overflow.
You are thinking in events, rather than thinking about HTTP and the web.
ASP.NET MVC embraces the HTTP protocol and you have to know what happens when a request is made and how HTML is rendered.
If you want to implement the scenario you are describing, you have to put a form on the page. The button can submit that form by making a POST request to some other action, and then the action can render a view showing the result. But for simply showing a message box, I don't think it is a good idea.
This is how desktop apps work, not web apps. You are trying to fit a square peg through a round hole.
there are many ways to get back to the controller. without post back look into ajax calls. the simplest way is the post back. put your view in a form tag either html or html.beginform
#using (Html.BeginForm()){
<input type="submit" value="submit"/>
}
as #Chuck mentioned on your controller then have a post method with the same name as the get you show
[HttpPost]
public ActionResult RegisterHour()
{
//TODO: do anything
return View(model);
}
the #Html.Action that you have will return a url so that is put inside another element. something like
<a src="#Html.Action("Action", "Controller")">Click Here</a>
if you want to stay in the same page instead of
return View("index");
use
return View();
Edit:
If you want a complete code of a do something stuff here you are:
Model
public ActionResult MyModel()
{
[Required]
public int propriety1 { get; set; }
}
Controller
public ActionResult DoSomething()
{
var model = new MyModel();
return View(model);
}
[HttpPost]
public ActionResult DoSomething(MyModel model)
{
if(ModelState.isValid){
//DO something
}else{
return View(model);
}
}
View
#model Models.MyModel
#using (Html.BeginForm())
{
#Html.LaberlFor(m=>m.propriety1) #Html.TextBoxFor(m=>m.propriety1)
<input type="submit" value="Click me" />
}
Create an endpoint and have the form submit to it.
UI Code
<form action="/Registration/RegisterHour" >
<p>
<label>Username</label>
<input type="text" name="username" />
</p>
<p>
<label>First Name</label>
<input type="text" name="firstname" />
</p>
<p>
<label>Last Name</label>
<input type="text" name="lastname" />
</p>
<p>
<label>Password</label>
<input type="text" name="password" />
</p>
<p>
<label>Confirm</label>
<input type="text" name="confirm" />
</p>
<input type="submit" value="Save" />
</form>
Model
public class Registration
{
public string Username {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string Password {get; set;}
public string Confirm {get; set;}
}
Typically you'll have two of the same endpoints, one is for the get, the other is for the post.
public class RegistrationController : Controller
{
//Get
[HttpGet]
public ActionResult RegisterHour()
{
//TODO: do anything
return View("Index");
}
//Post
[HttpPost]
public ActionResult RegisterHour(Registration newUser)
{
if(Model.IsValid)
{
//Save user to the database
userRepository.AddUser(newUser);
//load success screen.
return RedirectAction("SuccessfulRegistration");
}
//If Model is invalid handle error on the client.
return View("Index");
}
}

How To Pass Value Entered In A Text Box To An Action Method

I was building a Movies application using MVC. CRUD was automatically created for me by Visual Studio. Now, I am trying to build a Search functionality for the user. Here is the code I wrote:
#using (Html.BeginForm("SearchIndex", "Movies", new {searchString = ??? }))
{
<fieldset>
<legend>Search</legend>
<label>Title</label>
<input type ="text" id="srchTitle" />
<br /><br />
<input type ="submit" value="Search" />
</fieldset>
}
I have built the SearchIndex method and the associated view. I just can't find how to pass the value entered in the text box to the SearchIndex action method.
Please help.
In your Model:
public class Search
{
public String SearchText { get; set; }
}
Make your View strongly typed and use
#Html.EditorFor(model => model.SearchText)
In your Controller:
[HttpPost]
public ActionResult SearchIndex(Search model)
{
String text = model.SearchText;
}
Hope this helps.
You need to give your input field a name:
<input type="text" id="srchTitle" name="movieToFind" />
Then in your Controller make sure it has a string parameter:
in MoviesController:
[System.Web.Mvc.HttpPost]
public ActionResult SearchIndex(string movieToFind)
{
//Controller Action things.
}
Note: Form fields names must match the parameters expected in the controller. Or map to model properties if a 'Model' is expected.

Handling model state and validation in a complex view using multiple partials in ASP.NET MVC

I'm having a little trouble in getting my head around how to break up my views and actions into manageable chunks in ASP.NET MVC, and I've tried searching but I'm still none the wiser.
In order to try and just get my head around this particular aspect I've created a little test project where I try to understand the situation using the example of a login form and register form on the same page. My view model for this looks as below:
public class LoginOrRegisterModel
{
public LoginModel Login { get; set; }
public RegisterModel Register { get; set; }
public LoginOrRegisterModel()
{
this.Login = new LoginModel();
this.Register = new RegisterModel();
}
}
public class LoginModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
public class RegisterModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
I then started with thinking about the main action.
public ActionResult Index()
{
return View(new LoginOrRegisterModel());
}
...and view...
#model MvcSandbox.Models.LoginOrRegisterModel
#{
ViewBag.Title = "Index";
}
<h2>Login Or Register</h2>
#Html.Partial("Login", model: Model.Login)
#Html.Partial("Register", model: Model.Register)
...with partial views...
#model MvcSandbox.Models.LoginModel
#{
ViewBag.Title = "Login";
}
<h2>Login</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.EditorFor(model => model)
<button>Login</button>
}
#model MvcSandbox.Models.RegisterModel
#{
ViewBag.Title = "Register";
}
<h2>Register</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.EditorFor(model => model)
<button>Register</button>
}
I found that I had to make sure the properties of the LoginOrRegisterModel weren't null otherwise I got the error: The model item passed into the dictionary is of type 'MvcSandbox.Models.LoginOrRegisterModel', but this dictionary requires a model item of type 'MvcSandbox.Models.LoginModel'.
That's fine so far, although not very useful at the moment as both forms have the same field names and ids and both post back to an index page that does nothing.
HTML source:
<h2>Login Or Register</h2>
<h2>Login</h2>
<form action="/Membership" method="post"><div class="editor-label"><label for="UserName">UserName</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="The UserName field is required." id="UserName" name="UserName" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="Password">Password</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="The Password field is required." id="Password" name="Password" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span></div>
<button>Login</button>
</form>
<h2>Register</h2>
<form action="/Membership" method="post"><div class="editor-label"><label for="UserName">UserName</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="The UserName field is required." id="UserName" name="UserName" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="Password">Password</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="The Password field is required." id="Password" name="Password" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span></div>
<button>Register</button>
</form>
Anyway what I then looked to do, as I kind of wanted to keep the logic separate for each post, was make each form post to a different action. And this is where I think I'm going horribly wrong.
Essentially if validation fails I figured I needed to do something to try and actually build back up the model state when loading the page but I kind of got to what I have below and I'm kind of lost as to what approach I should be taking instead.
public class MembershipController : Controller
{
//
// GET: /Membership/
public ActionResult Index()
{
if (TempData["ModelState"] != null)
ModelState.Merge((ModelStateDictionary)TempData["ModelState"]);
return View(new LoginOrRegisterModel());
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
// do something
}
TempData["ModelState"] = ModelState;
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// do something
}
TempData["ModelState"] = ModelState;
return RedirectToAction("Index");
}
}
...with the views...
#model MvcSandbox.Models.LoginModel
#{
ViewBag.Title = "Login";
}
<h2>Login</h2>
#using (Html.BeginForm("Login", "Membership"))
{
#Html.ValidationSummary(true)
#Html.EditorFor(model => model)
<button>Login</button>
}
#model MvcSandbox.Models.RegisterModel
#{
ViewBag.Title = "Register";
}
<h2>Register</h2>
#using (Html.BeginForm("Register", "Membership"))
{
#Html.ValidationSummary(true)
#Html.EditorFor(model => model)
<button>Register</button>
}
The problem is because each model has fields of the same name validation is shown on both forms regardless of which is submitted, and when I've tried using an HtmlFieldPrefix I seem to get no validation at all.
Any advice on how I can break up my actions and views into manageable and maintainable chunks without giving myself this headache over model state and validation would be greatly appreciated.
UPDATE:
I've changed approach slightly to use partial actions which seems to improve things, code below:
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
if (TempData["LoginModelState"] != null)
ModelState.Merge((ModelStateDictionary)TempData["LoginModelState"]);
return View(new LoginModel());
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
// do something
}
TempData["LoginModelState"] = ModelState;
return RedirectToAction("Index");
}
public ActionResult Register()
{
if (TempData["RegisterModelState"] != null)
ModelState.Merge((ModelStateDictionary)TempData["RegisterModelState"]);
return View(new RegisterModel());
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// do something
}
TempData["RegisterModelState"] = ModelState;
return RedirectToAction("Index");
}
My index view is now:
#{
ViewBag.Title = "Index";
}
<h2>Login Or Register</h2>
#Html.Action("Login")
#Html.Action("Register")
And login and register:
#model MvcSandbox.Models.LoginModel
<h2>Login</h2>
#using (Html.BeginForm("Login", "Membership"))
{
#Html.ValidationSummary(true)
#Html.EditorFor(model => model)
<button>Login</button>
}
#model MvcSandbox.Models.RegisterModel
<h2>Register</h2>
#using (Html.BeginForm("Register", "Membership"))
{
#Html.ValidationSummary(true)
#Html.EditorFor(model => model)
<button>Register</button>
}
Now to me this has the advantage over the previous approach that it actually seems to work a little more and gets rid of need for the quite frankly horribly messy idea of the LoginOrRegisterModel which may be fine for such a simple example but would get messy very quickly as things got more complex and UIs got refactored with potentially lots of refactoring of models and potentially code as well as just views.
I really get the impression some replacing of the default model binder to have some sort of model binding based on a descriminator and having the controller action working as some sort of command processor such that it would fire off the correct handler based which partial was posted would be better, and resolve the refresh issue that comes from redirection as mentioned by Mystere Man below.
Don't use a redirect, as you lose model state. I know you are trying to fix that by passing model state in TempData, but the problem is that TempData is only valid for one access afterwards. If the users presses F5 or hits the refresh button, the model state is gone and things are even more messed up.
In general, only use TempData for things like showing an alert or message once to a user.
Using partial views like this is always a pain, particularly when trying to post a child model to a different form, as you have found out. The way I would do it is to use EditorTemplates instead of Partials, and then post your composite view model to both methods.
public ActionResult Login(LoginOrRegisterModel model)
{
if (ModelState.IsValid) {
// access only the Login properties, do same for Register
}
return View("LoginOrRegister", model)
}
In your view
...
#Html.EditorFor(m => m.LoginModel)
#Html.EditorFor(m => m.RegisterModel)
in ~/Views/Membership/EditorTemplates/LoginModel.cshtml (and RegisterModel.cshtml)
#model MvcSandbox.Models.LoginModel
// Not sure why you were setting the title in a partial view,
// particularly when you had two of them on a single page
<h2>Login</h2>
#using (Html.BeginForm("Login", "Membership"))
{
#Html.ValidationSummary(true)
#Html.EditorFor(model => model)
<button>Login</button>
}
The advantage of this is that it will correctly bind the parent model to the correct child model, and you can access whatever you want from that point forward.
You certainly can have multiple models and partials on a single "page" and post to separate actions - this is an approach that I used in this scenario. Also I've used this with "popup" dialogs and it works fine.
Regarding models, you basically either need to have a composite model (LoginOrRegisterModel) in the "parent" view then either use that same model in each "child" view (just use the bits you need in each) OR you have separate child models as properties off the parent model (LoginModel, RegisterModel). These are both valid approaches which will work but I think you get better separation with the second option (2 distinct child models).
Regarding posting, I would use AJAX to perform the separate form posts and then return partial views from the controller's individual post actions in the event of an error. I wouldn't attempt to use redirect to try and re-render the whole page due to the kind of problems you've already found.

Basic Problem with Asp.net MVC UpdateModel(myClass)

In my Controller in a Asp.net MVC 1 app I want to use UpdateModel to populate a variable with POST data in my controller. I've looked at dozens of examples but even the most basic ones seem to fail silently for me.
Here's a very basic example that's just not working.
What am I doing wrong?
public class TestInfo
{
public string username;
public string email;
}
public class AdminController : Controller
{
public ActionResult TestSubmit()
{
var test = new TestInfo();
UpdateModel(test);//all the properties are still null after this executes
//TryUpdateModel(test); //this returns true but fields / properties all null
return Json(test);
}
}
//Form Code that generates the POST data
<form action="/Admin/TestSubmit" method="post">
<div>
<fieldset>
<legend>Account Information</legend>
<p>
<label for="username">Username:</label>
<input id="username" name="username" type="text" value="" />
</p>
<p>
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</fieldset>
</div>
</form>
It looks like you're trying to get the controller to update the model based on the form elements. Try this instead:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestSubmit(TestInfo test)
{
UpdateModel(test);
return Json(test);
}
In your code, you're creating a new TestModel instead of letting the MVC runtime serialize it from the HttpPost. I've let myself get wrapped around the axel on this also, you're not the only one!
make properties of your public field:
public class TestInfo
{
public string username {get;set;}
public string email{get;set;}
}
I'm not too familiar with ASP.NET MVC, but shouldn't your TestSubmit method look more like this:
public ActionResult TestSubmit(TestInfo test)
{
UpdateModel(test);
return Json(test);
}
In the controller you should have two methods, one to respond to the GET, the other, if required is for responding to the POST.
So, firstly have a GET method:
public ActionResult Test ()
{
return View (/* add a TestInfo instance here if you're getting it from somewhere - db etc */);
}
Secondly, you'll need a POST method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test (TestInfo test)
{
return Json (test);
}
Notice that there's no UpdateMethod there, the ModelBinder would have done that for you.

Resources