I have the following Razor code:
<td>
<div class="editor-label">
#Html.LabelFor(model => model.AccountCode)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.AccountCode)
</div>
</td>
I would like to hard code the value 1001 as a default for the Input field. I have tried [model.accountcode ="1001"] which does not work.
Please explain with example code.
If you want to set a value in the model, that should be done in the controller...
public ActionResult MyAction()
{
var myModel = new ModelClass();
myModel.AccountCode = 1001;
return View("MyViewName", myModel);
}
Then use the normal syntax in Razor:
#Html.TextBoxFor(m => m.AccountCode)
Or if you just want a hidden parameter:
#Html.HiddenFor(m => m.AccountCode)
If you want to display some value directly in the textbox then you should try
#Html.TextBox("AccountCode", "1001")
Related
my problem it's kinda strange. So in a Index.cshtml i populate with data and in some place i use
#Html.Action("_Create")
To create a partialView where i populate with some data from the Server and with some empty fields that need to be completed for submit.
[HttpGet]
public PartialViewResult _Create()
{
var userOrder = _orderRepository.CurrentUser(User.Identity.GetUserName());
var something = new CurrentListOrderViewModel()
{
PersonName = userOrder.Select(p=>p.PersonName).FirstOrDefault(),
Funds = userOrder.Select(p=>p.Funds).FirstOrDefault(),
Order = "",
OrderCosts = 0,
Restaurant = "",
TodayOrderDate = DateTime.Now,
WindowsName = User.Identity.GetUserName()
};
return PartialView(something);
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult _Create([Bind(Include = "PersonName,Funds,Order,OrderCosts,WindowsName,TodayOrderDate")]CurrentListOrderViewModel model)
{
if(ModelState.IsValid)
{
return PartialView();
}
return PartialView(model);
}
So the problem is when the page loads with HTTPGET everything goes fine, the table get's populated from the database and if i change in the _Create.cshtml the #Html.EditorFor into something else so i can disable it, i lose the data. What could be the cause? I don't really understand it.
#model FoodOrderQubizInterfaces.ViewModel.Order.CurrentListOrderViewModel
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<tr>
<td>
#Html.EditorFor(model => model.PersonName)
#Html.ValidationMessageFor(model => model.PersonName)
</td>
<td>
#Html.EditorFor(model => model.Funds, new { htmlAttributes = new { disabled = "disabled" }, })
#Html.ValidationMessageFor(model => model.Funds)
</td>
<td>
#Html.EditorFor(model => model.Order)
#Html.ValidationMessageFor(model => model.Order)
</td>
<td>
#*#Html.DropDownListFor(model => model.Restaurant,*#
<select>
<option value="1">Bigys</option>
<option value="2">Zulu</option>
</select>
</td>
<td>
#Html.EditorFor(model => model.OrderCosts)
#Html.ValidationMessageFor(model => model.OrderCosts)
</td>
<td>
#Html.EditorFor(model => model.WindowsName)
#Html.ValidationMessageFor(model => model.WindowsName)
<input type="submit" value="Save/Modify" class="btn btn-default" />
</td>
<td>
#Html.EditorFor(model => model.TodayOrderDate)
#Html.ValidationMessageFor(model => model.TodayOrderDate)
</td>
<td>
</td>
</tr>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Hope you guys can help me with some advice cause i'm out of ideas
I found the problem, after i search the web for some time. The cause was when you submit and you have the disabled attribute added it will not add to the model cause he thinks the model is disabled so the user couldn't interact with it.
So to fix it i changed from
<td>
#Html.EditorFor(model => model.Funds, new { htmlAttributes = new { disabled = "disabled" }, })
#Html.ValidationMessageFor(model => model.Funds)
</td>
To
#Html.TextBoxFor(model => model.Funds, new { #readonly = true })
And in that was it keeps the data. I hope it will help someone else with my problem
I using code from this blog Autocompletion Textbox in MVC Using jQuery
but my jQuery isn't firing. I suspect its to do with my selector. I am using MVC as well but I don't see how that would make the javascript any different.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;
namespace UserManager.Controllers
{
public class UserManagerController : Controller
{
//
// GET: /UserManager/
public ActionResult Index()
{
try
{
var data = new UserManager.Models.UserManagerTestEntities();
return View(data.vw_UserManager_Model_Add_Users.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
public ActionResult CreateUser()
{
var data = new UserManager.Models.UserManagerTestEntities();
ViewBag.Message = "Create New User";
return View();
}
public ActionResult LookUpGroupName(string q, int limit)
{
//TODO: Map list to autocomplete textbox control
DAL d = new DAL();
List<string> groups = d.groups();
var GroupValue = groups
.Where(x => x.StartsWith(q))
.OrderBy(x => x)
.Take(limit)
.Select(r => new { group = r });
// Return the result set as JSON
return Json(GroupValue, JsonRequestBehavior.AllowGet);
}
}
}
#model UserManager.Models.vw_UserManager_Model_Add_Users
#{
ViewBag.Title = "Create New User";
}
<h2>
CreateUser</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>New User Details</legend>
<div class="editor-label">
#Html.LabelFor(Model => Model.salutation)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.salutation)
#Html.ValidationMessageFor(model => Model.salutation)
</div>
<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.password)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.password)
#Html.ValidationMessageFor(model => Model.password)
</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.isactive)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.isactive)
#Html.ValidationMessageFor(model => Model.isactive)
</div>
<div class="editor-label">
#Html.Label("Group Name")
<!-- GroupName -->
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.group_name)
#Html.ValidationMessageFor(model => Model.group_name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$("#group_name").autocomplete('#Url.Action("LookUpGroupName")',
{
dataType: 'json',
parse: function (data) {
var rows = new Array();
alert("before loop");
for (var i = 0; i < data.length; i++) {
rows[i] = { data: data[i], value: data[i].group, result: data[i].group }
}
return rows;
},
formatItem: function (row, i, max) {
return row.group
},
width: 300,
highlight: false,
multiple: true,
multipleseparator: ","
});
});
</script>
HTML rendered to browser:
<input name="group_name" class="text-box single-line" id="group_name" type="text" value=""/>
Probably something simple I just cant see it. Any ideas? Thanks!
I don't believe #Html.EditorFor(model => Model.group_name) adds and ID to the element it creates, therefor your selector will not match. You could add an ID like this:
#Html.EditorFor(model => Model.group_name, new { ID = "group_name"})
In addition, if you wan't to select on an ID with jquery it is better to use the ID-selector #group_name instead, unless you actually have a number of elements where the ID actually start with group_name for all of them, and you want to select all of the elements at once.
Update
You use the attribute start with selector input[id^=group_name, and have a typo in it. You are missing the closing ] in your selector. Even so, if you don't intent to select multiple elements that all have ID's that start with group_name, which your markup indicate that you don't. Then you should really use the ID selector instead.
Do a test run with this
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"Scala",
"Scheme"
];
$( "#group_name" ).autocomplete({
source: availableTags
});
});
When using MVC3 Razor this syntax will not work:
$("#postTags").autocomplete('<%=Url.Action("LookUpGroupName",) %>',
This is because Razor Engine doesn't understand WebForms Engine Syntax. Instead I used:
$("#group_name").autocomplete('#Url.Action("LookUpGroupName")',
I used the overloaded method which accepts ActionResult name only. This worked for me but you if your solution is setup differently you might have to supply both Controller and ActionResult arguements.
Finally I was getting error code 500 when my AJAX request was being made. This is because in my LookUpGroupName method I had to refactor this line of code:
return Json(GroupValue);
To:
return Json(GroupValue, JsonRequestBehavior.AllowGet);
My original post has all the correct code for anybodys future reference.
I have this model:
public class ExchangeRate
{
[Key]
public int ExchangeRateID { get; set; }
[Required]
[Display(Name = "Currency:")]
public string Currency { get; set; }
[Required]
public decimal Rate { get; set; }
}
The "Create" view is working fine, but when I am in the edit view, I only want the Currency property to be displayed, and not editable. How should I do this? If I create another "view-only" model for this class, then I would omit the "Currency" property and would not be able to display it.
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>ExchangeRate</legend>
#Html.HiddenFor(model => model.ExchangeRateID)
<div class="editor-label">
#Html.LabelFor(model => model.Currency)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.Currency)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Rate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Rate)
#Html.ValidationMessageFor(model => model.Rate)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Changing #Html.EditorFor(model => model.Currency) to #Html.DisplayFor(model => model.Currency) doesn't work because the model state becomes invalid when it posts back to the controller.
You could add
#Html.HiddenFor(model => model.Currency)
in your form and then use
#Html.DisplayFor(model=> model.Currency)
to display the readonly value of the currency property. That way when you post the value will be sent along in the posted model.
You're looking for:
[HiddenInput(DisplayValue=true)]
Then show the editor, not the display (use EditorFor).
This displays the value read-only, but adds a hidden input so that the posted state is valid.
To display the currency but not edit it try
#Html.Label("Currency", Model.Currency)
if you also need to post the currency value back to the controller try
#Html.HiddenFor(m => m.Currency)
I hope this helps.
I'm having lots of troubles.
I think that MVC just hates me.
1st. I'm using Linq and the model is automagically generated. I just completed the properties I need with the [Required] tag/directives.
2nd. I have a "Big Model" that joins two of the models.
Like is explained here -> Multiple models in a view
When I try to postback a view with a model that has those properties like nulls, is has the ModelState.isvalid == false. I think that is obvious because I set the [Required] to some of the properties that the model needs.
And here comes the thing that brought me here.
3rd. When I'm trying to use #Html.HiddenFor(...) my page won't postback.
If I use, let's say, 3 HiddenFor, the page does PostBack, but if I use 10 HiddenFor, the page just stand still. It does not go anywhere.
I've tried to do everything that is within my range of knowledge (very limited, I'm really new at MVC).
I've tried to bring to the view those properties and showing them up as if it were a "Detail View". Didn't succeed.
I've tried to set the #HiddenFor(model => model.Client). In the Action is passed as null.
I've tried to use these tons of HiddenFor.
I've tried to pass just an ID in the hidden (ClientID) and retrieve the object from the database, but the ModelState will not "update" its status once inside the action.
Why am I doing this?
I'm doing this because I need the pages to display the "Required Field Message" when a box isn't filled, hence, forbiding the page to postback without the data.
My database is fine, and those fields are "Not null", so, I can just remove the [Required] from the properties, but I would lose the "Required Field Message" (in addition to the PostBack that is the thing that I'm trying to avoid).
If anyone has the answer or an answer or whatever, please, post it... I'm about to shoot my head out xD
Thanks in advance...
PS: Sorry about my english... I know that it's not good (or even regular).
View
#model PruebaMVC.Models.OperacionModel
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Operación de Venta</legend>
#Html.HiddenFor(model => model.INMUEBLE)
#*#Html.HiddenFor(model => model.INMUEBLE.Direccion)*#
#*#Html.HiddenFor(model => model.INMUEBLE.Localidad)*#
#*#Html.HiddenFor(model => model.INMUEBLE.Ciudad)*#
#*#Html.HiddenFor(model => model.INMUEBLE.Caracteristicas)*#
#*#Html.HiddenFor(model => model.INMUEBLE.PrecioVenta)*#
#*#Html.HiddenFor(model => model.INMUEBLE.CLIENTE.IDCliente)*#
<div class="editor-label">
#Html.LabelFor(model => model.OPERACION.CLIENTE1.Nombre, "Nombre del Comprador")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OPERACION.CLIENTE1.Nombre)
#Html.ValidationMessageFor(model => model.OPERACION.CLIENTE1.Nombre)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OPERACION.CLIENTE1.Apellido, "Apellido del Comprador")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OPERACION.CLIENTE1.Apellido)
#Html.ValidationMessageFor(model => model.OPERACION.CLIENTE1.Apellido)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OPERACION.CLIENTE1.FechaNacimiento, "Fecha de Nacimiento del Comprador")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OPERACION.CLIENTE1.FechaNacimiento)
#Html.ValidationMessageFor(model => model.OPERACION.CLIENTE1.FechaNacimiento)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OPERACION.CLIENTE1.DNI, "DNI del Comprador")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OPERACION.CLIENTE1.DNI)
#Html.ValidationMessageFor(model => model.OPERACION.CLIENTE1.DNI)
</div>
<div class="editor-label">
#*#Html.LabelFor(model=>model.OPERACION.IDFormaPago, "Forma de Pago")*#
<label for="ComboFP">Forma de Pago</label>
</div>
<div class="editor-field">
<select id="ComboFP" name="SelectFP">
#{
foreach (PruebaMVC.Models.DatosLINQ.FORMA_PAGO item in PruebaMVC.Models.DatosLINQ.OperacionDatos.ListarFormaPago())
{
<option value="#(item.IDFormaDePago)">#(item.TipoPago)</option>
}
}
</select>
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OPERACION.Comision, "Comisión de la Venta")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OPERACION.Comision)
#Html.ValidationMessageFor(model => model.OPERACION.Comision)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OPERACION.Legajo, "Número de Legajo")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OPERACION.Legajo)
#Html.ValidationMessageFor(model => model.OPERACION.Legajo)
</div>
<p>
<input type="submit" class="formbutton" value="Cargar Venta" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Volver al listado de Inmuebles", "Index")
</div>
Controller
//
// GET: /Inmueble/Sale/5
public ActionResult VentaP(int id)
{
OperacionModel unModeloOperacionCompuesto = new OperacionModel();
unModeloOperacionCompuesto.INMUEBLE = InmuebleDatos.DetallesInmueble(id);
return View(unModeloOperacionCompuesto);
}
//
// POST: /Inmueble/Sale/5
[HttpPost]
public ActionResult VentaP(OperacionModel model, FormCollection collection)
{
try
{
// TODO: Add insert logic here
model.INMUEBLE = InmuebleDatos.DetallesInmueble(model.INMUEBLE.IDInmueble);
CLIENTE clienteComprador = new CLIENTE();
clienteComprador.Nombre = model.OPERACION.CLIENTE1.Nombre;
clienteComprador.Apellido = model.OPERACION.CLIENTE1.Apellido;
clienteComprador.DNI = model.OPERACION.CLIENTE1.DNI;
clienteComprador.FechaNacimiento = model.OPERACION.CLIENTE1.FechaNacimiento;
OPERACION nuevaOperacion = new OPERACION();
int unIDUsuario = UsuarioDatos.IDUsuario(User.Identity.Name);
int unIDFormaPago = Convert.ToInt32(collection["SelectFP"]);
decimal unaComision = model.OPERACION.Comision;
int unLegajo = model.OPERACION.Legajo;
if (ModelState.IsValid)
{
nuevaOperacion.INMUEBLE = model.INMUEBLE;
nuevaOperacion.FechaOperacion = DateTime.Now;
nuevaOperacion.IDUsuario = unIDUsuario;
nuevaOperacion.IDFormaPago = unIDFormaPago;
nuevaOperacion.INMUEBLE.IDEstado = 2;
nuevaOperacion.Monto = model.INMUEBLE.PrecioVenta;
nuevaOperacion.Comision = unaComision;
nuevaOperacion.Legajo = unLegajo;
nuevaOperacion.CLIENTE1 = clienteComprador;
nuevaOperacion.CLIENTE = model.INMUEBLE.CLIENTE;
OperacionDatos.CrearVenta(nuevaOperacion);
return RedirectToAction("Index");
}
else
{
//return View(nuevaOperacion);
return View(model);
}
}
catch
{
return View(model);
}
}
Edit 2:
I'm still touching the code, and when I comment the line of
#Html.HiddenFor(model => model.INMUEBLE.PrecioVenta)
Where "PrecioVenta" is a decimal(18,2), the page does post back... it is obviously still getting a ModelState.isValid == false because I'm having left that value.
What can I do?
Which are the primitive types for the "HiddenFor" will work?
Or is some stuff of the .Net Framework that can't "map" that datatype properly?
I think that the problem is the client side validations and decimals.
When you have a decimal value, it render it as "35,0" in your culture... but the javascript validator doesn't recognice the "," as a decimal coma.
This is a problem I'm having but I've found a post here in stackoverflow about modifying the javascript validator.
Here you can learn how to fix the javascript validator for decimals
I'm trying to create a forum. I'm trying to have the functionality of 'post edit' in 'thread details'
I have the standard OTB Thread index view, and when you click on 'details' it shows the OTB Thread details, I have added a foreach to display the posts relating to that thread underneath.
I'm now struggling with adding/allowing the posts that are displayed underneath to be edited. Specifically show/hide.
In context, all posts are 'hidden' until an administrator clicks a button to 'show' a post, and vice versa
Thread Controller:
public ViewResult Details(int id)
{
tb_SH_Forum_Threads tb_sh_forum_threads = db.tb_SH_Forum_Threads.Single(t => t.Thread_ID == id);
ViewBag.Private_ID = new SelectList(db.tb_SH_Forum_PrivateDesc, "Private_ID", "Private_Desc");
return View(tb_sh_forum_threads);
}
View:
#model Shareholder_Forum.Models.tb_SH_Forum_Threads
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>tb_SH_Forum_Threads</legend>
<div class="display-label">Thread_Title</div>
<div class="display-field">
#Html.DisplayFor(model => model.Thread_Title)
</div>
<div class="display-label">Thread_Details</div>
<div class="display-field">
#Html.DisplayFor(model => model.Thread_Details)
</div>
<div class="display-label">tb_SH_Forum_Categories</div>
<div class="display-field">
#Html.DisplayFor(model => model.tb_SH_Forum_Categories.Category_Description)
</div>
<div class="display-label">Thread_Date</div>
<div class="display-field">
#Html.DisplayFor(model => model.Thread_Date)
</div>
<div class="display-label">Replies</div>
<div class="display-field">
#Html.DisplayFor(model => model.Replies)
</div>
</fieldset>
#foreach
(var post in Model.tb_SH_Forum_Posts.Where(w => w.Private_ID == 1).OrderBy(o => o.Post_Date))
{
<div class ="post">
<fieldset>
<p class="post_details">At #post.Post_Date By #(post.Anon == true ? "Anonymous" : post.Username)
</p>
#post.Post_Desc
</fieldset>
</div>}
<p>
#Html.ActionLink("Back to List", "Index")|
</p>
I think I need to use RenderAction and/or Partial views, but I don't understand. Any advice, or point me in the right direction where I can learn about this.
As always, very much appreciated.
Not certain I understand what you want, but here's how you could do what I think you're asking.
#foreach (var post in Model.tb_SH_Forum_Posts.Where(w => w.Private_ID == 1).OrderBy(o => o.Post_Date))
{
if(post.IsEditable) //however you're determining if they can edit the post. Alternatively display both this and the else and use javascript to toggle which one you show
{
///...Your old view post code
}
else
{
#Html.RenderPartial("EditPost", new {postdata = post})
}
}
Make a model
public class PostDataViewModel
{
public Post PostData
{
get;
set;
}
}
EditPost.cshtml
#model PostDataViewModel
// The editable form and button to submit to SaveForumPost action
Save it with
public virtual ActionResult SaveForumPost(PostaDavaViewModel model)
{
//... save edits
// either return a redirect to Detail, or if you don't want to refresh the page call this with ajax
}