I've setup the default MVC 3 application and I'm new to it, but I've a problem when I'm trying to print a value from an input-field after I've clicked the submit button.
It's a simple register form with a submit button at the bottom. When I click the submit button nothing shall happen expect the text from one of the input-fields shall be printed to a label or something beneath the submit button. I'm totally lost on how to do this, I've tried to make a label with an id but I'm not able to get access to neither the input-fields value or the label.
Controller action looks like this:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
The complete form looks like this:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Firstname)
#Html.ValidationMessageFor(model => model.Firstname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Lastname)
#Html.ValidationMessageFor(model => model.Lastname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Phone)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Phone)
#Html.ValidationMessageFor(model => model.Phone)
</div>
<p>
<button id="btn_Register">
<span class="ui-button-text">Register</span>
</button>
</p>
</fieldset>
}
In order to get all the values from the posted form, they will be ( in your example ) within the person object.
To output a value in a label, you will need to modify the person object with the new value, and then on the View output this value.
e.g.
person.labelvalue = "foo";
<span>#model.labelvalue</span>
I suggest you take a look at asp.net/mvc as a starting base before moving from asp.net to asp.net mvc
You can have the way to go to the controller on button submit, get the input field value and set it on view to label you want to. However, if its just setting the label text on click of a button, then you don't need to have any server side code and so to say MVC code. Just use simple button instead of submit button. Write a JavaScript/jQuery event/function for button click and set the label text from required input-field. Something like...
$("#fooLabel").text($("#fooTextEditor").val());
To do this you will have to know the Ids of these two controls. As there is no built-in overload to provide Id to fields using #Html.EditorFor or #Html.LabelFor, you can either override HtmlHelper like suggested in this post..
How to specify ID for an Html.LabelFor<> (MVC Razor)
Or even simpler you can use any browser dev tool to find the generated Id for two controls and directly use them in your JaveScript/jQuery. Usually it is same as the model field name.
As you do not want to submit the page or any other action, you have to perform this action on the client side using java script or Jquery. In java script just add onclick event to btn_Register button and set the value of label to the text field. If you are using jquery in the click event assign the value as below
btn_Register.click(function(){
$("#label1").text($('txtfield1').val());
});
Related
This is a bit confusing. Till today i knew the following ways to pass data to view in MVC
ViewBag,ViewData,TempData,Strongly Typed Views and its Models.
So wherever we used a strongly typed view, we used to pass a model with data or empty object to a view, so that it does not throw any null reference error.
But today encountered a behavior that made me feel strange.
Case-1
The following is the EmployeeController's Create action
//
// GET: /Employee/Create
public ActionResult Create()
{
return View("Create");
}
The following is the CreateView inside Employee Folder or Views.
#model EmployeeDataBase.Models.Employee
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
I am not returning any model in the action,but still the view was rendered.
Case-2
My action
public ActionResult Create(Employee employee, Employee emp)
{
return View("Create");
}
Called the above using the following URL
http://localhost:50128/Employee/Create?Name=something
Both the Employee parameters in the action were instantiated with Name property value as "something". Did not return anything in the action, still create is rendered. If if a dynamically change the value of Name during debugging, its still shows "something" in Create view in the Name text box.
Case 1:
If you had passed a model into the view, it would have displayed that model. If you do not pass a model, the view simply uses your model class to create the controls. In this case it is creating labels, textboxes and validation for all the properties. It uses those lambda expressions in LabelFor (xxxFor) as Expression Trees and analyses your class. It analyses and looks for things like: In the model you may have used a Display("Full Name") attribute for Name property, therefore it will conclude you want to show "Full Name" in label instead of "Name". It creates validation javascript in the same manner.
Therefore, in order to use the expression tree given in lambdas, it does not need an instance of the model.
Case 2:
Has been addressed in this SO question.
Enviroment: Visual Studio 2012, MVC4, Razor, Internet Application.
I have a code with search form in the "View" page...
#using (Html.BeginForm("SearchResult", "Home", FormMethod.Get))
{
#Html.ValidationSummary(false)
<fieldset>
<legend>Contact Search</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input name="SearchButton" type="submit" value="Search" /></p>
</fieldset>
}
And then I'm sending a "model.Name" string directly to the JavaScript code using "#Model.Name".
The problem is... when I typing in the search form a quote (") symbol... for example... (10" android) I have a problem. JavaScript stops work somewhere. How can I check this "model.Name" string inside the controller is it contains (") or not and change it for JavaScript?
My JavaScript code... url += "&keywords=#Model.Name";
If "model.Name" is... 10" android ...will it work correct?
For Javascript, I would encode with "escape", but it is best practice to replace the " (double) quotes with the XML representation "
As for server-side, I use Web Protection Library from Microsoft to handle that part,
http://wpl.codeplex.com/
Microsoft.Security.Application.Encoder.HtmlEncode(HttpUtility.HtmlDecode(dr["message"].ToString()))
So I've got a form that gathers some data (including some HTML from a WYSIWYG box) and saves it to a database...
I now need to be able to let the user grab content for the WYSIWYG box from a local file. The user needs to be able to see the content in the WYSIWYG box before submitting the form proper.
I've tried adding a second form that acts as an uploader and in the controller action grabbing the file content, adding it to the model and then redirecting back to the same view but I don't know how to keep any data that has been entered in the fields of form 1 so...
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Create a New Mailing here:</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Mailing.Sender) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Mailing.Sender)%>
<%: Html.ValidationMessageFor(model => model.Mailing.Sender)%>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(model => model.Mailing.Body, new { #class = "body-editor", #id = "body-editor" })%>
<%: Html.ValidationMessageFor(model => model.Mailing.Body)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Mailing.Region, Model.Regions)%>
<%: Html.ValidationMessageFor(model => model.Mailing.Region)%>
</div>
<p>
<input type="submit" value="Create" id="submitMailing"/>
</p>
</fieldset>
<% } %>
<% using (Html.BeginForm("Upload", "Mail", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Load HTML from a file: </legend>
<input type="file" id="htmlFile" name="htmlFile" class="upload" />
<input type="submit" value="Engetenate" id="addContent"/>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
and
[HttpPost]
public ActionResult Upload(MailingViewModel m, HttpPostedFileBase htmlFile)
{
TryUpdateModel(m);
var reader = new StreamReader(htmlFile.InputStream);
m.Mailing.Body = reader.ReadToEnd();
return View("CreateMailing",m);
}
Any advice on what I'm missing or a better way to do it would be brilliant...
One way to tackle this problem would be to upload the file in the background as soon as the user selects it and once uploaded on the server store it temporarily. Then you could use AJAX to show the preview. As far as uploading the file in the background is concerned, well, you may take a look at the jquery form plugin which supports AJAX file uploads by generating a hidden iframe. And because of this AJAX simulated upload the other fields of the form won't be modified nor the page reloaded so values entered by the user will be preserved.
You may also take a look at this jQuery File Upload Demo.
I'm developing an ASP.NET MVC3 application using the new Razor view engine but I'm having some difficulty changing a TextBox so that it is multiline.
So far all I've been able to find via google is that I need to set the multiline property to true, but I'm not sure how.
View code looks like this.
<div class="editor-field">
#Html.TextBoxFor(model => model.Body)
</div>
Any suggestions?
You could decorate the Body property on your view model with the [DataType] attribute:
[DataType(DataType.MultilineText)]
public string Body { get; set; }
and in your view use the EditorFor helper instead of TextBoxFor:
<div class="editor-field">
#Html.EditorFor(model => model.Body)
</div>
Another possibility is to leave the model as is without adding any attributes to it and in your view use the TextAreaFor helper:
<div class="editor-field">
#Html.TextAreaFor(x => x.Body)
</div>
Personally I prefer the first approach.
This is how to curve the corners of the textbox in asp.net mvc4:
#HTML.TextBoxFor(Model => Model.Name)
I’m trying to do some validation in asp .net MVC 2.0 for my application. I want to have some nice client side validation. Validation should be done most time on model side with DataAnnotations with custom attributes( like CompareTo, StringLenght, MinPasswordLenght (from Membership.MinimumumpassworkdLenght value).
For that purpose I tried to use xval with jquery.validation.
Some specific thing is that most of forms will be working with ajax and most problems are when I want to validate form with ajax.
Here is link for sample project http://www.sendspace.com/file/m9gl54 .
I got two forms as controls ValidFormControl1.ascx, ValidFormControl2.ascx
<% using (Ajax.BeginForm("CreateValidForm", "Test", new AjaxOptions { HttpMethod = "Post" })) {%> <div id="validationSummary1">
<%= Html.ValidationSummary(true)%> </div> <fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.Name)%>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Name)%>
<%= Html.ValidationMessageFor(model => model.Name)%>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Email)%>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Email)%>
<%= Html.ValidationMessageFor(model => model.Email)%>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Password)%>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Password)%>
<%= Html.ValidationMessageFor(model => model.Password)%>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.ConfirmPassword)%>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.ConfirmPassword)%>
<%= Html.ValidationMessageFor(model => model.ConfirmPassword)%>
</div>
<p>
<input type="submit" value="Create" />
</p> </fieldset> <% } %> <%= Html.ClientSideValidation<ValidModel>()
.UseValidationSummary("validationSummary1", "Please fix the following problems:") %>
Both look same the difference is only validation summaryID (validationSummary1, validationSummary2). Both controls are rendered on one page :
Form2
<%Html.RenderPartial("~/Views/Test/ValidFormControl2.ascx", null); %>
Form1
<%Html.RenderPartial("~/Views/Test/ValidFormControl.ascx", null); %>
Validation property
First problem, when we have two controls with same type to validate it don’t work becosue html elements are rendered by field name ( so we have two element with same name “Password” ). Only first form will be validated by client side.
The worst thing is that even if we have different types and their fields name is same validation won’t work too ( this thing is what I need to repair it will be stupid to name some unique properites for validation ).
Is there any solution for this ?
Custom attributes validation
Next thing custom attributes validation ( All those error are when I use Ajax for on normal form validation is working without problem. ):
CompareTo - Simple compare to that is done in mvc template for account model ( class attribute saying with two property will be compared ) , and it wasn’t show on page. To do it I created own CachingRulesProvider with compareRule and my Attribute. Maybe there is more easy way to do it?
StringLenght with minimum and maximum value, I won’t describe how I done it but is there any easy whey to do it?
Validation summary
When I have two two control on page all summary validation information goes to first control validation summary element, even xval generated script say that elementID are different for summary. Any one know how to repair it?
Validation Information
Is there any option to turn on messages on place where is Html.ValidationMessageFor(model => model.ConfirmPassword). Becsoue for me it isn’t show up. I would like to have summary and near field information too not only red border. Any one know how to do it?
Ajax submit
Anyone know how to do easy without massive code in javascript to do submit via javascript. This will be used to change input submit to href element (a).
Both look same the difference is only validation summaryID
First off, I don't know why you want to have two controls, having two identical fields, one form. Each form should have its own model and use a model as a validator.
namespace Sample.Models
{
[metatype(typeof(PersonaValidation))]
public partial class Person
{
}
public class PersonValidation
{
[Required(ErrorMessage = "First name Required")]
[StringLength(20, ErrorMessage = "First name must be 20 or less characters in length")]
[DisplayName("First Name")]
public string Firstname { get; set; }
[Required(ErrorMessage = "Last name Required")]
[StringLength(20, ErrorMessage = "Last name must be 20 or less characters in length")]
[DisplayName("Last Name")]
public string Lastname { get; set; }
}
}
In your aspx, add the following script files before form tag:
<h2>Validation Sample</h2>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<div class="editor-label">
<%= Html.LabelFor(model => model.Firstname) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Firstname) %>
<%= Html.ValidationMessageFor(model => model.Firstname) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Lastname) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Lastname) %>
<%= Html.ValidationMessageFor(model => model.Lastname) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
This will work every time. Error message will be displayed next to the invalid field.
Concerning the ajax submit, you could just put a button on your form an then perform a click on it through jQuery. This would lead also lead to your form being posted.
You could also just make an ajax call to the controller action (on link click) and in here you post the necessary data from your form.