0

I have a CSS using this code

input[type="text"] {
    border: 1px solid #CCCCCC;
    border-radius: 5px 5px 5px 5px;
    box-shadow: none;
    padding: 5px 8px;
}

and the HTML page has the following code to use the CSS

<input id="product-name" type="text" required="required">

I want to use the Razor in the view to render the text box called product-name How can i do this ?

2 Answers 2

1

You could use the TextBox helper:

@Html.TextBox("product-name", null, new { required = "required" })

But personally I would recommend you to use a view model:

public class MyViewModel
{
    public string ProductName { get; set; }
}

and then have the controller action populate and pass this view model to the view:

public ActionResult Index()
{
    MyViewModel model = new MyViewModel();
    model.ProductName = "some product name";
    return View(model);
}

and now your view could be strongly typed to the view model:

@model MyViewModel
@Html.TextBoxFor(x => x.ProductName, new { required = "required" })
Sign up to request clarification or add additional context in comments.

5 Comments

And how can i control the text from .cs class ?
I have updated my answer with the proper way to do this using a view model. As an alternative you could set the value in ViewData from the controller action: ViewData["product-name"] = "some product name";. But personally that's not the approach I would recommend you. Strongly typed views and view models is the correct way to do ASP.NET MVC.
Using textBoxFor doesn't feel the CSS style, I should use class from css called text but It can't feel it even when I changed new{@class="text"} any idea about what to do /
well, It did works but one more thing while validating it with jQuery, it always return true even the box has no value. have you ever faced this problem before ?
Get rid of the required="required" attribute and decorate your view model property with the [Required] validation attribute. Now all you need to do is include the jquery.validate.unobtrusive.js and you will get automatic client side validation out of the box without the need to write any custom code.
0

You could just add the helper and add a class attribute to it to connect it to the css..

@Html.TextBox("name", null, new { id = "product-name", @class = "textbox", required = "required" });

and the css will change to

.textbox {
    border: 1px solid #CCCCCC;
    border-radius: 5px 5px 5px 5px;
    box-shadow: none;
    padding: 5px 8px;
}

1 Comment

And how can I control the input text from that text box in the .cs file ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.