I am trying to understand how web-services work and I think I need some help with my controller. For example, I am trying to add a user into my data base ... This is what I have:
public static Result addUser(){
DynamicForm form = Form.form().bindFromRequest();
String url = "http://my-url-qqq";
WSResponse response;
WSRequestHolder holder = WS.url(url);
holder.setHeader("Cookie", "sessionid="+ session("sessionid"));
Map<String,String> anyData = new HashMap();
JsonNode content = response.asJson();
// how can i put all this things togeter
//to put the elements from my form in
//my database ... ?
//and what is the role of all the pieces ?
return ok(index.render("Bello! Now you can log in!"));
}
And I have this model:
#Entity
public class registerForm extends Model {
//for registration
#Id
public String Id;
public String username;
public String first_name;
public String last_name;
public String password1;
public String re_password1;
....
}
routes:
GET /register controllers.Application.register()
POST /register controllers.Application.addUser()
and my html form:
<form action="#routes.Application.addUser()" method="POST">
<div class="col-md-offset-1 col-md-4">
<h3><b>Register : </b></h3>
<br>
Username :
<input type="input" name="username" class="form-control"><br>
First Name :
<input type="input" name="first_name" class="form-control"><br>
Last Name :
<input type="input" name="last_name" class="form-control"><br>
Email :
<input type="input" name="email" class="form-control"><br>
Password:
<input type="password" name="password" class="form-control"><br>
Repeat Password :
<input type="password" name="re_password" class="form-control"><br>
<input type="submit" class="btn">
<br><br><br><br>
<h2> ^_^ : have fun .</h2>
</div>
</form>
Can anyone explain/translate how to connect this things ?
I'll appreciate any kind of example ...
First dont use DynamicForm when your form has same structure like your entity class means DynamicForm are used when For ex. if you want to search user from database then your form will have only one field in that case you can use DynamicForm where you can search from predefined entity field.If your form have same field like your entity fields
Second I think you misunderstood entity i.e. entity is a POJO(Plane Old Java Object) your class represent a table in database and your entity name is registrationforn and I think thats not look good you should name your entity like User or Member.This is completely optional for you but it gives better understanding
To save data do
public static Result addUser(){
registerForm user = Form.form(registerForm.class).bindFromRequest().get;
user.save(); //and the data is saved
return ok(index.render("Hello! Now you can log in!"));
}
And delete, find entity etc check Play Ebean Sample Application.
Related
I would like to create a form in my asp.net MVC website, without using HTML helpers like #Html.EditorFor()...
I also want to use Jquery Mobile.
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset data-role="controlgroup" data-iconpos="right">
<legend>Languages :</legend>
<input type="checkbox" name="checkbox-h-6a" id="checkbox-h-6a">
<label for="checkbox-h-6a"></label>
<input type="checkbox" name="checkbox-h-6b" id="checkbox-h-6b">
<label for="checkbox-h-6b">French</label>
<input type="checkbox" name="checkbox-h-6c" id="checkbox-h-6c">
<label for="checkbox-h-6c">German</label>
</fieldset>
}
I would like to use it with my model. (for ex. "bool UseEnglish", "bool UseFrench",..)
How can I do it simply ?
The only thing the helpers really do is abstract the name attributes of the form fields away. If you don't want to use the helpers, you will just have to make sure the name attributes are set to the right thing so that they will match up to your model after POST.
For simple properties, the name is just the property name, so given:
public string Foo { get; set; }
You'd have an input like:
<input type="text" name="Foo">
For things like complex types or reference navigation properties, you'll just chain the property names together until you're at the level you need, so given:
public Foo Foo { get; set; }
And:
public class Foo
{
public string Bar { get; set; }
}
You'll end up with:
<input type="text" name="Foo.Bar">
Finally, for list-style properties, you'll just add an index, so given:
public List<string> Foos { get; set; }
Then:
<input type="text" name="Foos[0]">
<input type="text" name="Foos[1]">
<input type="text" name="Foos[2]">
And of course, you can put all of these principles together to model any relationship:
public List<Foo> Foos { get; set; }
Then:
<input type="text" name="Foos[0].Bar">
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.
Hi I am trying to convert the following HTML input into razor html.textbox helper using vb syntax
<input type="text" name="q" data-autocomplete-source="#Url.Action("QuickSearchTransactionNumber", "Home")" class="form-control" id="TransactionNumber" placeholder="Transaction Number">
Any help would be great
You can add custom attributes to HTML elements created by HTML helpers by defining a new dictionary like so:
#Html.TextBox("q", Request("q"),
New Dictionary(Of String, Object) From
{
{ "data-autocomplete-source", Url.Action("QuickSearchTransactionNumber", "Home")},
{"class", "form-control"}, {"id", "TransactionNumber"},
{"placeholder", "Transaction Number"}
})
This outputs the following HTML:
<input class="form-control" data-autocomplete-source="/Home/QuickSearchTransactionNumber" id="TransactionNumber" name="q" placeholder="Transaction Number" type="text" value="" />
Documentation for this overload: http://msdn.microsoft.com/en-us/library/dd505258(v=vs.108).aspx
If you want to use a LabelFor in your view (that's strongly typed to a model) you can do this:
#Html.LabelFor(Function(model) model.BranchNumber, New With { .class = "sr-only" })
You also have to annotate your data model with a Display attribute like so:
Imports System.ComponentModel.DataAnnotations
Public Class Bank
Private _branchNumber As String
<Display(Name:="Branch Number")>
Public Property BranchNumber() As String
Get
Return _branchNumber
End Get
Set(ByVal value As String)
_branchNumber = value
End Set
End Property
End Class
I'm trying to perform remote validation on a property of an item within a collection. The validation works OK on the first item of the collection. The http request to the validation method looks like:
/Validation/IsImeiAvailable?ImeiGadgets[0].ImeiNumber=123456789012345
However on the 2nd item where the url looks like below, the validation doesn't work
/Validation/IsImeiAvailable?ImeiGadgets[1].ImeiNumber=123456789012345
Now I'm pretty sure the reason for this, is that binding wont work on a collection that doesn't begin with a zero index.
My validation method has a signature as below:
public JsonResult IsImeiAvailable([Bind(Prefix = "ImeiGadgets")] Models.ViewModels.ImeiGadget[] imeiGadget)
Because I'm passing an item within a collection I have to bind like this yet what I'm really passing is just a single value.
Is there anyway I can deal with this other than just binding it as a plain old query string.
Thanks
Edit: This is the quick fix to get the Imei variable but I'd rather use the model binding:
string imeiNumber = Request.Url.AbsoluteUri.Substring(Request.Url.AbsoluteUri.IndexOf("=")+1);
Edit: Here is my ImeiGadget class:
public class ImeiGadget
{
public int Id { get; set; }
[Remote("IsImeiAvailable", "Validation")]
[Required(ErrorMessage = "Please provide the IMEI Number for your Phone")]
[RegularExpression(#"(\D*\d){15,17}", ErrorMessage = "An IMEI number must contain between 15 & 17 digits")]
public string ImeiNumber { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
You could write a custom model binder:
public class ImeiNumberModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var modelName = bindingContext.ModelName;
var request = controllerContext.HttpContext.Request;
var paramName = request
.Params
.Keys
.Cast<string>()
.FirstOrDefault(
x => x.EndsWith(modelName, StringComparison.OrdinalIgnoreCase)
);
if (!string.IsNullOrEmpty(paramName))
{
return bindingContext
.ValueProvider
.GetValue(request[paramName])
.AttemptedValue;
}
return null;
}
}
and then apply it to the controller action:
public ActionResult IsImeiAvailable(
[ModelBinder(typeof(ImeiNumberModelBinder))] string imeiNumber
)
{
return Json(!string.IsNullOrEmpty(imeiNumber), JsonRequestBehavior.AllowGet);
}
Now the ImeiGadgets[xxx] part will be ignored from the query string.
If you are posting the whole collection, but have a nonsequential index, you could consider binding to a dictionary instead
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
If you're only posting a single item or using a GET link, then you should amend to
/Validation/IsImeiAvailable?ImeiNumber=123456789012345
and
public JsonResult IsImeiAvailable(string imeiNumber)
If you are sending up a single value to the server for validation, then your Action Method should only accept a scalar (single-value) parameter, not a collection. Your URL would then look like this (assuming default routing table for {controller}/{action}/{id}:
/Validation/IsImeiAvailable?ImeiNumber=123456789012345
the corresponding action method signature could look like this:
/* note that the param name has to matchthe prop name being validated */
public ActionResult IsImeiAvailable(int ImeiNumber)
EDIT:
which you could then use to lookup whether that particular ID is available.
if you want to change the name of the parameter, you can modify the routing table, but that's a different topic.
The long story short of it is that if you wanted to do validate a collection of ImeiGadget, you'd GET or POST that full collection. For a single value, it doesn't make much sense to send up or to expect an entire collection.
UPDATE:
Based on new info, I would look at where the remote validation attribute is being placed. It sounds like it might be placed on something like an IEnumerable<IMEiGadgets>, like this:
[Remote("IsImeiAvailable", "Validation", "'ImeiNumber' is invalid"]
public IEnumerable<ImeiGadget> ImeiGadgets { get; set;}
Would it be possible to move that attribute and modify it to be on the ImeiGadget class instead, to be something like this?
[Remote("IsImeiAvailable", "Validation", "'ImeiNumber is invalid"]
public int ImeiNumber { get; set;}
In theory, you shouldn't have to change anything on your HTML templates or scripts to get this working if you also make the change suggested in my answer above. In theory.
Unless you need this binding feature in many places and you control the IsImeiAvailable validation method then I think creating a custom model binder is an over-head.
Why don't you try a simple solution like this,
// need little optimization?
public JsonResult IsImeiAvailable(string imeiNumber)
{
var qParam = Request.QueryString.Keys
.Cast<string>().FirstOrDefault(a => a.EndsWith("ImeiNumber"));
return Json(!string.IsNullOrEmpty(imeiNumber ?? Request.QueryString[qParam]), JsonRequestBehavior.AllowGet);
}
You can add an extra hidden field with .Index suffix to allow arbitrary indices.
View:
<form method="post" action="/Home/Create">
<input type="hidden" name="products.Index" value="cold" />
<input type="text" name="products[cold].Name" value="Beer" />
<input type="text" name="products[cold].Price" value="7.32" />
<input type="hidden" name="products.Index" value="123" />
<input type="text" name="products[123].Name" value="Chips" />
<input type="text" name="products[123].Price" value="2.23" />
<input type="hidden" name="products.Index" value="caliente" />
<input type="text" name="products[caliente].Name" value="Salsa" />
<input type="text" name="products[caliente].Price" value="1.23" />
<input type="submit" />
</form>
Model:
public class Product{
public string Name{get; set;}
public decimal Price{get; set;}
}
Controller:
public ActionResult Create(Product[] Products)
{
//do something..
}
For more information refer to : You've Been Haacked: Model Bindig To A List
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.