MVC - How to simply do something at button click? - asp.net-mvc

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

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.

What should I do when more than one submit cases exist

I have a form where I fill in a blank and then save it, which takes me to the read only version of the entry I've just saved. At this step I have 2 options:
Either "Confirm" or "Cancel". Both actions will update some values in the database, so they're both good candidates for submit button(HttpPost, of course). I know this shouldn't be tied to a particular web development technology as
all-in-all it's all about Request and Response, but still I'll talk in ASP.NET MVC "language" as that is what I'm using now. So far, the only idea that has come to my mind is to have a separate submit buttons with different names and on the server side check for the name and act accordingly. But this seems a bit ugly to me as I might have to have a huge and universal action method. Do you have any better approach? Maybe MVC has some built in way for this purpose?
huge and universal action method
That's entirely your responsibility. You write action methods to map HTTP requests to business logic.
public class PostModel<T>
{
public string SubmitAction { get; set; }
public T TheModel { get; set; }
}
public ActionResult HandleSomePost(PostModel<Foo> model)
{
switch (model.SubmitAction.ToUpperInvariant())
{
case "SAVE":
_yourBLL.Save(model.TheModel);
break;
case "CANCEL":
_yourBLL.Cancel(model.TheModel);
break;
default:
throw new ArgumentException("SubmitAction");
}
return View();
}
Then you can handle both submit buttons from this form:
#using (Html.BeginForm("HandleSomePost", "TheController", FormMethod.Post))
{
#Html.EditorFor(m => m.TheModel)
<input type="submit" name="SubmitAction" value="Cancel">
<input type="submit" name="SubmitAction" value="Save">
}
However, this will quickly become a mess. You can also use attributes to let submit buttons map to action methods (though for simplicity I removed the "action:" prefix used for localization, be sure to read that Q&A and the linked blog):
[HttpPost]
[MultipleSubmit(SubmitAction = "Save")]
public ActionResult Save(Foo model)
{
_yourBLL.Save(model);
return View();
}
[HttpPost]
[MultipleSubmit(SubmitAction = "Cancel")]
public ActionResult Cancel(Foo model)
{
_yourBLL.Cancel(model);
return View();
}
You could do this with 2 forms, each posting to different action methods:
<form method="post" action="/cancelAction">
<input name="id" type="hidden" value="some-id-value">
<input type="submit" value="Cancel">
</form>
<form method="post" action="/confirmAction">
<input name="id" type="hidden" value="some-id-value">
<input type="submit" value="Confirm">
</form>
Or using MVC Razor syntax since you mentioned it:
#using (Html.BeginForm("cancelAction", "MyController", FormMethod.Post))
{
#Html.HiddenFor(model => model.ID)
<input type="submit" value="Cancel">
}
#using (Html.BeginForm("confirmAction", "MyController", FormMethod.Post))
{
#Html.HiddenFor(model => model.ID)
<input type="submit" value="Confirm">
}
From the information above it seems hard to pin down the exact use case here, however it might not be neccessary to have both a post for the confirm and cancel.
Consider using the submit event for "confirmation" and then just call the cancel event using normal HTTP-GET and passing the item that needs to be cancelled's ID? Then you can either handle the confirm or cancel events in either of the Actions directly or do a RedirectToAction to the HugeUniversalAction.
#using (Html.BeginForm("Confirm","ExampleController",FormMethod.Post))
{
<input type/>
<input type="submit" value="confirm"/>
#Html.ActionLink("Cancel", "ExampleController", id = Model.Id)
}
Then in your controller you can call the larger universal method.
public ActionResult Cancel(int id)
{
// Cancel directly
// or
return RedirectToAction("HugeUniversalAction", new { confirm = "false", id = id });
}
[HttpPost]
public ActionResult Confirm(Foo model)
{
// Confirm Directly
// or
return RedirectToAction("HugeUniversalAction", new { confirm = "true", id = model.Id });
}
Then handle the two paths in whichever way you need to in your HugeUniversalAction
public ActionResult HugeUniversalAction(int id, confirm = false){ // If confirm confirm it else cancel it }

ASP.NET MVC Html.BeginForm decodes URL

I'm requesting ASP.NET MVC the controller using the URL like this:
http://mysite.com/controller/myaction/Invalid%23name%25x
where Invalid%23name%25x is a parameter to
public ActionResult MyAction(string id) {
return View();
}
The GET request works fine.
MyAction view looks like this:
#using (Html.BeginForm()) {
...
<input name="Save" type="submit" value="Save" />
}
The generated HTML is:
<form action="/Controller/MyAction/Invalid#name%x" method="post">
...
<input name="Save" type="submit" value="Save" />
</form>
When I click on "Save", the form gets posted and the POST request goes to
http://mysite.com/controller/myaction/Invalid#name%x
i.e. the initial URL is decoded. This means the the POST action receives only the first part of the parameter - "Invalid"
[HttpPost]
public ActionResult MyAction(string id, ...) {
return View();
}
How can I prevent Html.BeginForm from decoding the initial URLs in order to preserve the initial state?
Pass ActionName and Controller in your form
#using (Html.BeginForm("ActionName", "Controller")) {
I would personally recommend you not to use id as string because as you have seen string can have many words in it.. let it mean what usually it does(numeric value).
use something like http://mysite.com/controller/myaction?Name=Invalid%23name%25x
public ActionResult MyAction(string Name) {
return View();
}
I suppose this would work for you..

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