getting values View data in controller - asp.net-mvc

i did this all but now how to get values being typed in Textbox, password box etc in CONTROLLER. I defined all necessary methods, boxes and buttons etc. So the only problem is to get values in controller and then to send them to model for accessing db data
.csHtml
#using (Html.BeginForm("register","Home", FormMethod.Post, new {id="submitForm"}))
{
<div>
<i>#Html.Label("Name:")</i>
#Html.TextBox("txtboxName")
</div>
<div>
<i>#Html.Label("Email:")</i>
#Html.TextBox("txtboxEmail")
</div>
<div>
<i>#Html.Label("Password:")</i>
#Html.Password("txtboxPassword")
</div>
<div>
<button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
</div>
}
Controller code:
namespace LoginSys.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Registration";
return View();
}
[HttpPost]
public ActionResult register(string command, FormCollection formData )
{
if (command == "submit")
{
var name = formData["txtboxName"];
var email = formData["txtboxEmail"];
}
return View();
}
}
}
i'm intentionally using this way of coding it instead of complex and advance one. Just help me to get values in controller

[HttpPost]
public ActionResult register(YOURMODEL model)
{
//db operation
return View();
}
NOTE: make sure your textbox name should be same as your model name

You should use viewmodels. create a model for the view that can be posted to the action. However, if you wish to continue your current approach you need to change the controller action to something like this:
[HttpPost]
public ActionResult register(string btnSubmit, string txtboxName, string txtboxEmail, string txtboxPassword)
{
if (command == "submit")
{
}
return View();
}
if this doesn't work, you can test it by using this:
[HttpPost]
public ActionResult register(FormCollection form)
{
if (command == "submit")
{
}
return View();
}
When you debug you can check the 'form' parameter and see that your fields exists in the form, and get the proper names for the parameters you need.

Related

Hijacked Umbraco HttpPost action not firing

I've hijacked the route in Umbraco 7.1 and for some reason my HttpPost is not firing when the submit button is pressed. Any input as to why this is? There is a postback taking place when send is pressed but the when putting a break point in the HttpPost it's never fired.
Here's a snippet of my code, the markup followed by the controller.
#inherits UmbracoViewPage
#{
Layout = "Layout.cshtml";
}
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.TextAreaFor(m => m.Message)
< i n p u t type="submit" value="Send" />
#Html.ValidationMessageFor(m => m.Message)
</div>
}
public ActionResult Index(ManageMessageId? smess)
{
var errorModel = new ErrorModel();
...
return CurrentTemplate(errorModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ErrorModel model)
{
if (ModelState.IsValid)
{
...
}
return View();
}
Assuming you are using SurfaceControllers, you would want to create your form as follows. Note the change in how you create the form and how the generic and parameter match that of the surface controller:
#using (Html.BeginUmbracoForm<MyController>("Index"))
{
}
Your controller should look something like:
public class MyController : SurfaceController
{
public ActionResult Index(ManageMessageId? smess)
{
var errorModel = new ErrorModel();
...
return CurrentTemplate(errorModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ErrorModel model)
{
if (ModelState.IsValid)
{
...
}
return View();
}
}

How can i do search inside same page in MVC Razor

How can i do search inside same page in MVC Razor? For example; my page do not any result when open if i search return.i must use IEnumerable<model> for getting result but if i use IEnumerable<model> for empty page, i am getting error.
Search page
#model IEnumerable<SearchResult>
<span>Search results:</span>
<p>
#foreach(var item in Model)
{
#item.Title<br/>
}
</p>
You need to return empty model for such case. for example in controller code:
public ActionResult Test()
{
// some actions
return View(new List<SearchResult>());
}
in that case it will send empty model, and won't fail.
You can create a model that contain the search properties and the result list.
Model
Public class MySearchModel{
public string searchInput { get; set; }
public List<mySearchResultModel> resultList { get; set; }}
Controller
public ActionResult Index()
{
var model = new MySearchModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MySearchModel model)
{
model.searchInput //filter
model.mySearchResultModel = //query where filter
return View(model);
}
View
#model MySearchModel
<div>
#Html.LabelFor(x => x.searchInput)
#Html.TextBoxFor(x => x.searchInput)
</div>
<span>Search results:</span>
#foreach (var item in Model.mySearchResultModel){
#item.Title<br />
}
Another way to accomplish the same is to add your search inputs and map them to the controller action that you are posting using the input name:
Controller
public ActionResult Index()
{
var model = new mySearchResultModel();
return View(model);
}
[HttpPost]
public ActionResult Index(mySearchResultModel model, string searchInput)
{
model.mySearchResultModel = //query where filter (searchInput)
return View(model);
}
View
#model IEnumerable<mySearchResultModel>
<input type="text" name="searchInput"/>
Search results:
#foreach(var item in Model) { #item.Title<br/> }

Model change in post action not visible in Html.TextBoxFor?

This must be something very obvious but for me it looks very strange. I have simple controller, model with one property, and view which displays value of property and renders editor for that property. When I click the button, form is posted and exclamation mark is appened to property. This exclamation mark is visible in my view but only in p tag, not in input tag rendered by Html.TextBoxFor().
Why Html.TextBoxFor() ignores that I updated my model in post action?
Is there any way to change this behavior of Html.TextBoxFor()?
View
#model ModelChangeInPostActionNotVisible.Models.IndexModel
#using (Html.BeginForm())
{
<p>#Model.MyProperty</p>
#Html.TextBoxFor(m => m.MyProperty)
<input type="submit" />
}
Model
namespace ModelChangeInPostActionNotVisible.Models
{
public class IndexModel
{
public string MyProperty { get; set; }
}
}
Controller
namespace ModelChangeInPostActionNotVisible.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new IndexModel { MyProperty = "hi" });
}
[HttpPost]
public ActionResult Index(IndexModel model)
{
model.MyProperty += "!";
return View(model);
}
}
}
HTML after clicking on submit button
<form action="/" method="post"> <p>hi!</p>
<input id="MyProperty" name="MyProperty" type="text" value="hi" /> <input type="submit" />
</form>
This is by design.
The helper methods are using the ModelState, thus if the response of your request is using the same Model, it will display the value that was posted.
This is to allow you to render the same view in the situation where the validation would have failed.
To make sure you display the new information add : ModelState.Clear(); before you return.
Read more here : http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx
namespace ModelChangeInPostActionNotVisible.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new IndexModel { MyProperty = "hi" });
}
[HttpPost]
public ActionResult Index(IndexModel model)
{
model.MyProperty += "!";
ModelState.Clear();
return View(model);
}
}
}
Yan Brunet is absolutely correct that the variable needs to be removed from the ModelState in order to be modified in the controller. You don't have to clear the entire ModelState, though. You could do the following to remove just the variable to want to modify:
ModelState.Remove("MyProperty");
This would be useful in case you wanted to retain other values which the user had entered.

How do I create a httppost getting same parameters from httpget?

I have a controller to show up a model (User) and want to create a screen just with a button to activate. I don't want fields in the form. I already have the id in the url. How can I accomplish this?
Use [ActionName] attribute - this way you can have the URLs seemingly point to the same location but perform different actions depending on the HTTP method:
[ActionName("Index"), HttpGet]
public ActionResult IndexGet(int id) { ... }
[ActionName("Index"), HttpPost]
public ActionResult IndexPost(int id) { ... }
Alternatively you can check the HTTP method in code:
public ActionResult Index(int id)
{
if (string.Equals(this.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
{ ... }
}
A bit late to the party on this but I found an easier solution to what I think is a fairly common use-case where you prompt on GET ("are you sure you want to blah blah blah?") and then act on POST using the same argument(s).
The solution: use optional parameters. No need for any hidden fields and such.
Note: I only tested this in MVC3.
public ActionResult ActivateUser(int id)
{
return View();
}
[HttpPost]
public ActionResult ActivateUser(int id, string unusedValue = "")
{
if (FunctionToActivateUserWorked(id))
{
RedirectToAction("NextAction");
}
return View();
}
On a final note, you can't use string.Empty in place of "" because it must be a compile-time constant. And it's a great place to put funny comments for someone else to find :)
You could use a hidden field inside the form:
<% using (Html.BeginForm()) { %>
<%= Html.HiddenFor(x => x.Id) %>
<input type="submit" value="OK" />
<% } %>
or pass it in the action of the form:
<% using (Html.BeginForm("index", "home",
new { id = RouteData.Values["id"] }, FormMethod.Post)) { %>
<input type="submit" value="OK" />
<% } %>
My approach is not to add an unused parameter as that seems like it would cause confusion, and is in general bad practice. Instead, what I do is append "Post" to my action name:
public ActionResult UpdateUser(int id)
{
return View();
}
[HttpPost]
public ActionResult UpdateUserPost(int id)
{
// Do work here
RedirectToAction("ViewCustomer", new { customerID : id });
}
The easiest way for such simple situation is to give a name to submit button and check in action if it has value or not.
If it has the value, then it Post action, if not, then it Get action :
<% using (Html.BeginForm("index", "home",
new { id = RouteData.Values["id"] }, FormMethod.Post)) { %>
<input type="submit" value="OK" name="btnActivate" />
<% } %>
For Cs you can combine get and post controller methods in one:
public ActionResult Index(int? id, string btnActivate)
{
if (!string.IsNullOrEmpty(btnActivate))
{
Activate(id.Value);
return RedirectToAction("NextAction");
}
return View();
}

Model Binding using ASP.NET MVC, getting datainput to the controller

Pretty Basic one here guys.
I have a View which holds 2 textfields for input and a submit button
<%using (Html.BeginForm("DateRetrival", "Home", FormMethod.Post)){ %>
<%=Html.TextBox("sday")%>
<%=Html.TextBox("eday")%>
<input type="submit" value="ok" id="run"/>
<% }%>
the following controller action which I want to bind the data input is as follows
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult DateRetrival()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string submit)
{
return null;
}
When I debug this and look in the action methods parameter, the value is null. When I've entered values in both textboxes and and clicked the submit method.
You probably want to do something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string sday, string eday)
{
return null;
}
Ideally, though you probably want to be passing a model to your controllers:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(DateModel dates)
{
var date1 = dates.sday;
var date2 = dates.eday;
return null;
}
See http://msdn.microsoft.com/en-us/library/dd394711.aspx
Add parameters to catch each input field value.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string sday, string eday)
{
return null;
}
Try:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string sday, string eday, string submit)
{
return null;
}
and if you want sumbit button value
<input type="submit" value="ok" id="run" name="submit"/>
If you want to have value posted, name attribute has to be set. Html.TextBox automatically sets name from parameter.

Resources