Rectangle 27 6

Those are simple HTML attributes, so you could use any attribute available in the DOCTYPE you are using. ASP.NET MVC helpers simply take those attributes and emit them in the resulting HTML page. So if you need a documentation take a look at the HTML specification.

There is just a little remark about HTML5 data-* attributes which contain dashes. Because dashes cannot be used as variable names in .NET you could use underscore which will be converted to a dash. Example:

@Html.TextBoxFor(x => x.Foo, new { data_id = "bar" })
<input type="text" name="Foo" id="Foo" value="some value" data-id="bar" />

Thanks Darin always fast and concise. Does that mean that I can use any pair {attribute_name, attribute_value.ToString()}?

and a special case of class attribute use the following @Html.TextBoxFor( x => x.Foo, new { @class = "cssClassName" } )

jquery - What are the html attributes for html helpers in ASP.NET MVC3...

c# jquery asp.net-mvc html-helper html
Rectangle 27 2

You can consider just creating your HTML helpers to render emails and return it as a string.

Doesn't really matter whether it is partial view or a method returning a string with HTML. i actually think that for your case helper methods would be a better choice.

A simple helper method is also more flexible in the ways you can use it.

asp.net mvc - Render View (or Partial) In another project? - Stack Ove...

asp.net-mvc path view render partial
Rectangle 27 3

No, ASP.NET MVC doesn't remember checkbox values after they're submitted. Being an HTTP application as soon as ASP.NET MVC has rendered the HTML it ends the request and forgets everything about what it's just done. Then upon submitting a form ASP.NET MVC processes the incoming HTTP request and maps it to your model via its model binding (more on how it does this in a moment).

Having come from a PHP background myself this is one of those questions I always had when starting with ASP.NET MVC.

With ASP.NET MVC you have to remember that you're working within the context of a complete framework, and in order to ensure you're as productive as possible ASP.NET MVC will take care of a lot of the mundane work for you - ASP.NET MVC's model binding is a perfect example of this.

When submitting a form, the ASP.NET MVC framework will parse all incoming post data and attempt to automatically map it to the values you're providing it via your controller action.

So where as in PHP you'd normally do something along the lines of:

if(isset($_POST['checkboxValue'])) {
    $checkboxVal = $_POST['checkboxValue'];
}
[HttpPost]
public ActionResult Submit(bool checkboxValue){
}

It does this by checking the parameter name (checkboxValue) matches that of the post data array key, and that the type also matches up. For instance, if you were to change the above checkboxValue from a boolean to a string and change the name, then ASP.NET MVC's model binding will be unable to match the property to the post data and will not automatically set the value for you.

It's also worth noting that ASP.NET MVC's model binding doesn't know how you created the checkbox.

The HTML.CheckBox and HTML.CheckBoxFor html helpers are purely a means to make it easier for you to create the HTML. If you were to manually write the HTML yourself then the model binder will still successfully bind the submitted data.

As @DrinkBird has quite rightly pointed out, you're also able to access all of your form's post data by using the FormCollection instance like so:

[HttpPost]
public ActionResult Submit(FormCollection postData){
}

This collection represents all of the data posted to the Submit action.

You can also use the FormCollection parameter that includes every data posted back to the server.

asp.net mvc - Does MVC remember checkbox values after submit? - Stack ...

asp.net-mvc razor checkbox
Rectangle 27 3

Sometimes the HTML helpers don't HELP. DropDownListFor coding can get complicated real fast and in the end it's just rendering HTML so sometimes it's better to go old school

<select name="myname" class="dropdownlist" id="myid">
    @foreach (SelectListItem item in Model.SomeSelectList) {
        if (item.Value ==  Model.theValue) {
            <option value="@(item.Value)" selected="selected">@item.Text</option>
        } else {
            <option value="@(item.Value)">@item.Text</option>
        }
    }
</select>

asp.net mvc - Can I change the html name generated by Html.DropDownLis...

asp.net-mvc asp.net-mvc-3
Rectangle 27 1

Because MVC is stateless, there is no concept of state management like webforms. In other words, you cannot simply "enable" or "disable" a link in the sense that you're asking. You seem to be doing it correctly, albeit a little more verbose than you need to. You do a post and your action methods make the decision to enable/disable the link before the view is rendered, then your view must check if it's allowed to show the link or not. You could then pass along a model property like this:

@(Model.TopicWatchLink ? Html.ActionLink("Video", "Play", new { topicId = topic.TopicId }) : "N/A")

That is basically what you're doing already, but placed in an inline IF to take up less space.

Another option you might consider is @Html.RenderAction("someAction"). This allows you to call an action method (and pass in parameters if you wish) from your view when it's being rendered. You could then put the logic that determines whether or not to show the view in the said action method and have the action return the link html. While you could put the HTML in a string, I recommend you define a partial view or use the TagBuilder class to build your link and return it. Ex:

public MvcHtmlString GenerateLink(bool enabled)
{
    if (enabled)
    {
        var tagBuilder = new TagBuilder("a");
        tagBuilder.MergAttribute("src", Url.Action("Video", "Play")); // Pseudo-code
        return tagBuilder.ToString(TagRenderMode.SelfClosing);
    }
    else
        return "N/A";
}

Then in your view:

@Html.RenderAction("GenerateLink", new { enabled = Model.TopicWatchLink }); // Pseudo-code

Some of that is pseudo-code (i.e. has not been tested and may not exactly match the real code) but you get the idea. You could also do this in an html helper.

See here for details on creating HTML helpers. If it were me I would use ActionLink in a custom helper and just accept a boolean that would determine what to render.

There are a number of different options available to you. Just remember that MVC is stateless and it's up to you to make those kinds of logic decisions as well as implement them. It might be easier in webforms to call linkButton.Disabled = true; but you have not idea what ASP.NET does to disable it. Basically you have no control over how the disabling happens and you can remain ignorant to the underlying HTML/CSS. MVC is about working intimately with this process. It might be more verbose that setting disabled to true, but in my opinion it is worth doing to see through the abstraction.

c# - How to disable an HyperLink in ASP.NET MVC3 with Html Helpers wit...

c# asp.net-mvc-3 hyperlink html-helper
Rectangle 27 1

Because MVC is stateless, there is no concept of state management like webforms. In other words, you cannot simply "enable" or "disable" a link in the sense that you're asking. You seem to be doing it correctly, albeit a little more verbose than you need to. You do a post and your action methods make the decision to enable/disable the link before the view is rendered, then your view must check if it's allowed to show the link or not. You could then pass along a model property like this:

@(Model.TopicWatchLink ? Html.ActionLink("Video", "Play", new { topicId = topic.TopicId }) : "N/A")

That is basically what you're doing already, but placed in an inline IF to take up less space.

Another option you might consider is @Html.RenderAction("someAction"). This allows you to call an action method (and pass in parameters if you wish) from your view when it's being rendered. You could then put the logic that determines whether or not to show the view in the said action method and have the action return the link html. While you could put the HTML in a string, I recommend you define a partial view or use the TagBuilder class to build your link and return it. Ex:

public MvcHtmlString GenerateLink(bool enabled)
{
    if (enabled)
    {
        var tagBuilder = new TagBuilder("a");
        tagBuilder.MergAttribute("src", Url.Action("Video", "Play")); // Pseudo-code
        return tagBuilder.ToString(TagRenderMode.SelfClosing);
    }
    else
        return "N/A";
}

Then in your view:

@Html.RenderAction("GenerateLink", new { enabled = Model.TopicWatchLink }); // Pseudo-code

Some of that is pseudo-code (i.e. has not been tested and may not exactly match the real code) but you get the idea. You could also do this in an html helper.

See here for details on creating HTML helpers. If it were me I would use ActionLink in a custom helper and just accept a boolean that would determine what to render.

There are a number of different options available to you. Just remember that MVC is stateless and it's up to you to make those kinds of logic decisions as well as implement them. It might be easier in webforms to call linkButton.Disabled = true; but you have not idea what ASP.NET does to disable it. Basically you have no control over how the disabling happens and you can remain ignorant to the underlying HTML/CSS. MVC is about working intimately with this process. It might be more verbose that setting disabled to true, but in my opinion it is worth doing to see through the abstraction.

c# - How to disable an HyperLink in ASP.NET MVC3 with Html Helpers wit...

c# asp.net-mvc-3 hyperlink html-helper
Rectangle 27 14

Look at the generated HTML. In ASP.NET MVC 3 Beta there's new support for unobtrusive jquery based ajax and all the Ajax helpers use jquery now. Maybe there's something left with MS Ajax which causes the double call. Make sure you remove all the inclusions of MSAjax scripts from the page. Also why using Ajax.BeginForm when you could simply use Html.BeginForm with unobtrusive jquery?

Than you, it worked after I removed the reference to the old MSAjax scripts!

asp.net mvc 3 - Form submitted twice after updating from ASP MVC 3 Pre...

asp.net-mvc-3
Rectangle 27 14

Look at the generated HTML. In ASP.NET MVC 3 Beta there's new support for unobtrusive jquery based ajax and all the Ajax helpers use jquery now. Maybe there's something left with MS Ajax which causes the double call. Make sure you remove all the inclusions of MSAjax scripts from the page. Also why using Ajax.BeginForm when you could simply use Html.BeginForm with unobtrusive jquery?

Than you, it worked after I removed the reference to the old MSAjax scripts!

asp.net mvc 3 - Form submitted twice after updating from ASP MVC 3 Pre...

asp.net-mvc-3
Rectangle 27 17

You can certainly use any mix of client-side rendering and server-side rendering, but I would recommend against trying to mix ASP.NET MVC helpers with AngularJS directives. It might seem like a good idea at first because you're already used to using those helpers and you don't have to write "raw html", but they defeat the some of the purpose of what client-side applications try to achieve: separation of concerns, responsiveness, data-binding, and testability.

There's definitely a place for making mini-SPAs within a larger, traditional web-application, especially if you're converting a legacy application or if parts of the larger application don't need a SPA or are best served without it. But if you're going to render a given page - or part of page - on the client, then buy in completely and let AngularJS do what it knows how to do.

So let's say you have a Products model (some enumerable list of ) and you want to render that on the page in a list. You have three options I can think of:

  • Use a razor @ForEach and render it server-side, but accept that your client-side AngularJS application won't know about this list and won't bind it to its model
  • Wait until the page loads and AngularJS bootstraps, then make an API call to your MVC server-side application for some JSON data and stick it in the model. Use ng-repeat to render the list.
  • Use razor to serialize the Products model on the server into some JSON string and embed that in the AngularJS controller you send back. Use ng-repeat to render the list and take advantage of client-side data-binding.

The last option is ugly. I can't think of a really good reason for it, unless you need client-side data-binding and you have to pay for each API call.

The first would be good if you don't need any data-binding on the client (it's a read-only list) or you need SEO.

The second is the way I would do it in most scenarios. You've decided to use AngularJS for a reason - let it do its job.

Don't use MVC helpers just because they're there. AngularJS provides its own directives that do much the same stuff. And if you need more, write your own. Part of using a client-side framework is buying in to the philosophy: the server is responsible for server-y stuff like authentication, server validation, and providing data through an API, and the client is responsible for being a front-end application. Keep your concerns separate.

None of this means you can't use ASP.NET MVC for routing, authentication, or the overall structure of your app. All that surrounds your AngularJS apps. Once you're inside a mini-SPA, though, do it the SPA way.

This is philosophy I've used when integrating ASP.NET MVC with AngularJS. The server-side MVC is responsible solely for rendering the initial page, and then providing a semi-RESTful API after that. It uses ASP.NET MVC to route URLs, authenticate, and other goodies. But there's almost no razor and definitely no HTML helpers.

asp.net-mvc angularjs mvc
Rectangle 27 2

a user control is just some stuff that renders html, in mvc you have html helpers and partial views and normal views (you can render them with renderaction )

Html.Helper("someStuff")
Html.RenderPartial("viewname")
Html.RenderAction<Controller>(o => o.Action());

you can actually easily substitute a call to

Html.TextBoxFor(o => o.Name);

with

Html.RenderPartial("textbox", Model.Name);

ASP.NET MVC : Good Replacement for User Control? - Stack Overflow

asp.net-mvc user-controls
Rectangle 27 3

That happens because HTML helpers always use the values in the request before the ones in the model when rendering a value. This basically means that if you want to modify some value in the POST action you need to remove it from the model state first:

[HttpPost]
public ActionResult Widget(WidgetModel m)
{
    ModelState.Remove("SelectedWidgetId");
    m.SelectedWidgetId = 2;
    return View(m);
}

or the helper will simply ignore the value you are manually setting and use the one that was POSTed by the user.

asp.net mvc - Why does SelectList SelectedValue work on HttpGet but no...

asp.net-mvc asp.net-mvc-3 html-select selectlist
Rectangle 27 2

I think this is because when you use something like @Html.HiddenFor( m => m.Id ) the html helpers look in various places to populate the input's value, and the values in the route is one of those places.

template/customize/{TemplateId}
public ActionResult Customize(int templateId)

OR you could change your viewmodel (or create a custom view model) that has a CustomizationId property rather than just Id.

And no, it's not a bug... it's more of a feature that can have unforeseen consequences. But once you're aware of it, it works like a treat.

I realize that I'm probably bending the rules and breaking a few of them as well. Definitely feeling the pain of that, but I still feel like m.Id should always be the Model.Id not the Route.Id unless model doesn't exist in the context.

You lead me to an acceptable solution so I'm marking your answer. Following up with an edit containing what I did.

Just want to clarify, that any of your other solutions would have worked as well (and the route would have been more elegant). I just didn't want to create a new route in my route table.

Why why why does it get a value from a route rather than element on a form? Do you happen to know where I can read more about this? Thank you

I buy this as a feature if you are using a dynamic typed model, but that's not the case. You won't even be able to add a hidden to another route parameter because the HiddenFor will expect an expression wich returns a memberexpression pointing to a property of the model type. As an example, you won't be able to do Html.HiddenFor(x=> x.Controller)

.net - ASP.NET MVC 3 Model Id using Route Id value - Stack Overflow

.net asp.net asp.net-mvc asp.net-mvc-3 html-helper
Rectangle 27 2

I think this is because when you use something like @Html.HiddenFor( m => m.Id ) the html helpers look in various places to populate the input's value, and the values in the route is one of those places.

template/customize/{TemplateId}
public ActionResult Customize(int templateId)

OR you could change your viewmodel (or create a custom view model) that has a CustomizationId property rather than just Id.

And no, it's not a bug... it's more of a feature that can have unforeseen consequences. But once you're aware of it, it works like a treat.

I realize that I'm probably bending the rules and breaking a few of them as well. Definitely feeling the pain of that, but I still feel like m.Id should always be the Model.Id not the Route.Id unless model doesn't exist in the context.

You lead me to an acceptable solution so I'm marking your answer. Following up with an edit containing what I did.

Just want to clarify, that any of your other solutions would have worked as well (and the route would have been more elegant). I just didn't want to create a new route in my route table.

Why why why does it get a value from a route rather than element on a form? Do you happen to know where I can read more about this? Thank you

I buy this as a feature if you are using a dynamic typed model, but that's not the case. You won't even be able to add a hidden to another route parameter because the HiddenFor will expect an expression wich returns a memberexpression pointing to a property of the model type. As an example, you won't be able to do Html.HiddenFor(x=> x.Controller)

.net - ASP.NET MVC 3 Model Id using Route Id value - Stack Overflow

.net asp.net asp.net-mvc asp.net-mvc-3 html-helper
Rectangle 27 2

TwitterBootstrapMVC is a library of html helpers, main focus of which is to simplify writing html related to Twitter Bootstrap forms.

As of today it works with Twitter Bootstrap 2 syntax. However, support for Twitter Bootstrap 3 will be released shortly.

If you used helpers from tihs library, transition from v2 to v3 should be painless.

Disclaimer: I'm the author of TwitterBootstrapMVC The BMVC for Bootstrap 3 is not free.

Is there a solution for using ASP.NET MVC 5 Html.EditorFor() and Boots...

asp.net-mvc twitter-bootstrap twitter-bootstrap-3 asp.net-mvc-5
Rectangle 27 2

You don't have to create html helpers in your controller. You should create partial view returning captcha and return PartialViewResult:

public PartialViewResult Captcha()
{
    return PartialView("Captcha");
}

I agree. This is always something that is best left to a PartialView and not something you'd render in a controller method. Separate out presentation and leave it to a View.

Awesome. Works like a charm! Thanks!

ASP.NET MVC - How do I render an HtmlHelper method in a controller? - ...

asp.net-mvc
Rectangle 27 1

You could use view models which have class and property names matching those requirements. Because I suppose that even if you find a way to modify how those attributes are generate by HTML helpers you will also want to bind values back to some view models when the form is submitted. So in addition to this you will have to write custom model binders to handle this situation which might become quite a lot of a job.

Hi Darin, Thx for the (very) quick reply! We already have a custom model binder which is able to fill the complex object structure from the incoming http request. It is also already prepared to handle those 'shortnames'. In fact we have a quick prototype that uses the first possible solution I mentioned (copy pasting all the source code we need, including some internal methods from the framework). Is this legal? I hope someone could come up with a cleaner solution.

It is legal; it's open source, with a compatible license.

I prefer adapting the framework source to our needs above having classes with unreadable names :) But I guess using your approach is another way to go..

asp.net mvc - Changing the generated id and name attributes - Stack Ov...

asp.net-mvc
Rectangle 27 4

Declarative helpers in Razor are static methods. You could pass the Html helper as argument:

@helper DisplayForm(HtmlHelper html) {
    @html.EditorForModel(); 
}

@DisplayForm(Html)

When I try this I get the error "CS1061: 'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'EditorForModel' and no extension method 'EditorForModel' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)"

@model MyNs.Models.FooViewModel

asp.net mvc - Using html helpers in Razor web helper - Stack Overflow

asp.net-mvc razor
Rectangle 27 1

One way to skip using JSON would be to look for certain elements within the returned HTML. If you're using any of the html helpers for validation messages (Html.ValidationSummary(), Html.ValidationMessageFor()) these will render elements with specific classes you can look for to decide the outcome. If not, you can make your own standards.

For example, if you're using the Html.ValidationSummary-method, it will render a list with the class validation-summary-errors. So you can set a variable like this and then handle the response accordingly.

var isValid = $(response).find(".validation-summary-errors").length == 0;

So in your situation:

success: function (result) {
    var isValid = $(result).find(".validation-summary-errors").length == 0;

    //If Successful, reload Survey Partial View
    if (isValid) {
         $('#surveyBox').html(result);
    }
    //If Validation Failed reload form with validation errors
    else {
        $('#editSurveyModal').html(result);
    }
}

This is probably what I'll end up doing. Seems hackish. I'll keep you posted.

asp.net - Return a Partial View In JSON from a Controller in MVC - Sta...

asp.net asp.net-mvc ajax json
Rectangle 27 4

ASP.NET MVC 3 now honors the IValidateObject interface when model binding (in addition to all of the other validation approaches it already supported with MVC 2), and will retrieve validation errors from it and automatically flag/highlight impacted fields within a view using the built-in HTML form helpers.

ASP.NET MVC 3 also introduces a new IClientValidatable interface that allows ASP.NET MVC to discover at runtime whether a validator has support for client validation. This interface has been designed so that it can be integrated with a variety of validation frameworks. MVC 3 also introduces a new IMetadataAware interface that simplifies how you can contribute to the ModelMetadata creation process.

This is all related to adding client side validation to Validation Attributes which as I stated in my question, works very well. I am asking about adding client side validation to IValidatableObject.

asp.net mvc 3 - IValidatableObject in MVC3 - client side validation - ...

validation asp.net-mvc-3 client-side-validation
Rectangle 27 39

That's how HTML helpers work and it is by design. They will first look in the POSTed data and after that in the model. So for example if you have:

<% using (Html.BeginForm()) { %>
    <%= Html.TextBoxFor(x => x.Name) %>
    <input type="submit" value="OK" />
<% } %>

which you are posting to the following action:

when the view is redisplayed the old value will be used. One possible workaround is to remove the value from the ModelState:

[HttpPost]
public ActionResult Index(SomeModel model)
{
    ModelState.Remove("Name");
    model.Name = "some new name";
    return View(model);
}

Tried it in a very similar scenario.. doesn't seem to work. Any help will be appreciated here - stackoverflow.com/questions/12138552/

This helped me so much, thank you! To the person who closed this question: you need to know what's being asked here before making your judgement whether this question is worth anything or not!!

asp.net mvc - MVC - change model's value in view on post - Stack Overf...

asp.net-mvc asp.net-mvc-2