ASPNET MVC 5 Html helper Action method view result

2019-06-09 22:45发布

问题:

To recreate the issue I'm having I've set up two simple controller actions, two views and a view model:

MultiForms Action (in the form controller class)

public class FormController : Controller
{
    [HttpGet]
    public ActionResult MultiForms()
    {
        return View("MultiForms");
    }

    // ...

MultiForms.cshtml - Razor View

@Html.Action("MyFormGet", "Form")

Notice in the action method I call the controller method that returns the form partial view.

MyFormGet Action

[HttpGet]
public PartialViewResult MyFormGet()
{
    var viewModel = new MyFormViewModel();
    ViewData.TemplateInfo.HtmlFieldPrefix = Guid.NewGuid().ToString().Replace("-", "_");
    return PartialView("MyForm", viewModel);
}

View Model

public class MyFormViewModel
{
    public string TextInput1 { get; set; }
}

MyForm.cshtml - Razor View

@model Mvc5App.Controllers.MyFormViewModel

@using (Html.BeginForm("MyFormPost", "Form", FormMethod.Post))
{
    <br />
    @Html.TextBoxFor(m => m.TextInput1)
}

When I point my browser at /Form/MultiForms I get the output I expect:

<input type="text" value="" name="e166fa0d_46fe_40d4_a970_73c52a35f224.TextInput1" id="e166fa0d_46fe_40d4_a970_73c52a35f224_TextInput1">

Then I refresh the page and the output becomes this:

<input type="text" value="" name="48edc339_69ad_4b9b_9583_198038beab45.TextInput1">

Where did the id attribute go? Is this a bug in ASPNET MVC5 or have I done something wrong with this setup?

回答1:

Thanks to @demo I think I figured out when the id doesn't show up...

If the id starts with a digit(or underscore) it will not render. So this GUID will render:

f3b1a447_3786_4472_9dfe_14c3ae8aae24

But this one will not:

1c26ce3d_5c71_408a_aae2_7be414f1d383

The solution for the above seems to be prefixing with something like this:

FOO_1c26ce3d_5c71_408a_aae2_7be414f1d383

And the problems go away.