2013-05-07 14 views
5

In ASP.NET MVC, ho scritto qui di seguito il codice per dare al testo un valore iniziale:Il valore di default per TextBoxFor in ASP.NET MVC

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", 
             @class = "mustInputText noime w50", 
             maxlength = "8", @Value = "0", 
             rule = "InputOnlyNum" }) 

E il sorgente HTML è la seguente:

<input Value="0" class="mustInputText noime w50" id="WEIGHT" maxlength="8" 
    name="WEIGHT" rule="InputOnlyNum" tabindex="140" type="text" value="" /> 

mi si accorge che ci sono due attributi valore nel tag "input": Value="0" e value=""

come farlo mostrare un solo attributo valore?

risposta

7

Uso TextBox invece di TextBoxFor

@Html.TextBox("WEIGHT", Model.WEIGHT ?? "0", new {...}) 

o se il peso è una stringa vuota

@Html.TextBox("WEIGHT", Model.WEIGHT == "" ? "0" : Model.WEIGHT, new {...}) 
3

Bene, hai esplicitamente dichiarato Value, non value.

Prova:

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8", @value = "0", rule = "InputOnlyNum" }) 
+0

No, che doesn' lavoro. –

+0

Mostra solo valore = "" –

1

testato, ma provate TextBox anziché TextBoxFor, in quanto ha un sovraccarico per passare il valore come secondo parametro.

@Html.TextBox(p => p.WEIGHT, "0", 
    new { tabindex = "140", @class = "mustInputText noime w50", 
      maxlength = "8", @Value = "0", rule = "InputOnlyNum" }) 

L'altra opzione è quella di impostare i valori predefiniti nel costruttore della classe del modello che inizializza PESO.

5

Sembra essere il comportamento predefinito. Se vuoi veramente evitare gli attributi del doppio valore, è meglio seguire il modo più pulito impostando il valore predefinito nel metodo di creazione della classe controller. Questo segue l'ideologia del pattern MVC.

//GET 
public ActionResult CreateNewEntity() 
{ 
    YourEntity newEntity= new YourEntity(); 
    newEntity.WEIGHT= 0; 

    return View(newEntity); 
} 

Poi sulla vostra vista, non sarà necessario utilizzare l'attributo più il valore:

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", 
             @class = "mustInputText noime w50",  
             maxlength = "8", 
             rule = "InputOnlyNum" }) 

il codice HTML risultante è:

<input class="mustInputText noime w50" 
     id="WEIGHT" 
     maxlength="8" 
     name="WEIGHT" 
     rule="InputOnlyNum" 
     tabindex="140" 
     type="text" 
     value="0" /> 
0

Forse questo? Non testato.

@Html.TextBoxFor(p => (p.WEIGHT==null ? 0 : p.WEIGHT), new { tabindex = "140", 
     @class = "mustInputText noime w50", 
     maxlength = "8", 
     rule = "InputOnlyNum" }) 
0
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8", 
@value = model.WEIGHT==null?"0":model.WEIGHT, rule = "InputOnlyNum" }) 
Problemi correlati