0
votes

This is my CreateUnit.cshtml where I set the templateId into the hidden input field with the id 'TemplateId'. When I confirm the dialog the asp.net mvc controller 'UnitController' and its action method 'Create' is executed which should pass the UnitViewModel. Inside the UnitViewModel the model binder has set the name property to the value I entered. But the templateId from the hidden field is missing.

Why this?

@model ITMS.Web.Models.UnitViewModel

@*Remote Validation*@
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {
        var templateId = $('#MyDialog').data('templateIdKey');
        $('#TemplateId').text(templateId);       
    }); 

</script>

@using (Html.BeginForm("Create", "Unit"))
{ 
     @Html.ValidationSummary(false)
    <p class="editor-label">@Html.LabelFor(model => model.Name)</p>
    <p class="editor-field">@Html.EditorFor(model => model.Name)</p>
    <p class="editor-field">@Html.ValidationMessageFor(model => model.Name)</p> 

    @Html.HiddenFor(x => x.TemplateId)      
}

[HttpPost]
public ActionResult Create(UnitViewModel unitViewModel)
{
    if (ModelState.IsValid && !_dataProvider.UnitExists(unitViewModel.Name, unitViewModel.TemplateId))
    {
        Unit unit = Mapper.Map<UnitViewModel, Unit>(unitViewModel);
        _dataProvider.AddUnit(unit);
        return new JsonNetResult(new { success = true });
    }
    ModelState.AddModelError("Name", "This name already exists.");
    return PartialView(unitViewModel);
}

 public class UnitViewModel
    {
        [Required(ErrorMessage = "Name must not be empty.")]
        [StringLength(30, ErrorMessage = "Enter max. 30 chars for a name.")]
        [Remote("UnitExists", "Unit", ErrorMessage = "This name already exists.",AdditionalFields="TemplateId")]
        [JsonProperty("title")]
        public string Name { get; set; }  

        public Nullable<int> ParentId { get; set; }

        [HiddenInput(DisplayValue = false)]
        public int TemplateId { get; set; }
    }
2

2 Answers

0
votes

Instead of @Html.HiddenFor(x => x.TemplateId) in your view, use @Html.EditorFor(x => x.TemplateId) instead. The HTML will be rendered as a hidden input field.

0
votes

Instead of:

$('#TemplateId').text(templateId);

I wrote this and now the TemplateId is sent with the form :)

$("[name='TemplateId']").val(templateId);

stupid from me the input field has no text ...