开发者

How to create a custom Html.ValidationMessage?

This is my Controller:

/// <summary>
/// Activity
/// </summary>
/// <returns></returns>
public ActionResult CreateActivity()
{
    AriaCRMEntities aria = new AriaCRMEntities();
    var unit = from u in aria.ActivityGroupIDs select u;
    List<SelectListItem> lst = new List<SelectListItem>();
    foreach (var u in unit)
    {
        lst.Add(new SelectListItem { Text = u.ActivityGroupName.ToString(), Value = u.ActivityGroupID_FK.ToString() });
    }
    ViewData["activity"] = lst;
    return View();
}

[HttpPost]
public ActionResult CreateActivity(FormCollection model)
{

        if (ModelState.IsValid)
  开发者_Python百科      {
            Activity activ = new Activity();
                if (!string.IsNullOrEmpty(model["ActivityGroupID_FK"]))
                {
                    AriaCRMEntities aria = new AriaCRMEntities();
                    activ.ActivityGroupID_FK = Int32.Parse(model["ActivityGroupID_FK"]);
                    activ.ActivityType = model["ActivityType"];
                    activ.ActivityDes = model["ActivityDes"];
                    aria.Activities.AddObject(activ);
                    aria.SaveChanges();
                    return RedirectToAction("Create");
                }
        }
        return View(model);
}

This is my View :

<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true,) %>
<fieldset>
    <legend>Fields</legend>
<br />
<%:Html.DropDownListFor(model=>model.ActivityGroupID_FK , (IEnumerable<SelectListItem>)ViewData["activity"], "انتخاب نوع فعالیت")%><br /> 
<%Html.ValidationMessageFor (model=>model.ActivityGroupID_FK,"dddddddddd"); %>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.ActivityType) %>
    </div>
    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.ActivityType) %>
        <%: Html.ValidationMessageFor(model => model.ActivityType,"dfsaaa") %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.ActivityDes) %>
    </div>
    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.ActivityDes) %>
        <%: Html.ValidationMessageFor(model => model.ActivityDes) %>
    </div>
    <p>
        <input type="submit" value="Create" id="btn"/>
    </p>
</fieldset>
<% } %>

But now I need to validate <%:Html.DropDownListFor%>. How do I create custom validation?


If you want to display a validation error message next to your drop-down list, you can do this from your controller like so:

ModelState.AddModelError("ActivityGroupID_FK", "The selected value is invalid.");

Update

I just noticed the validation message for your DropDownList looks like this:

<%Html.ValidationMessageFor (model=>model.ActivityGroupID_FK,"dddddddddd"); %>

You might want to change that like so:

<%: Html.ValidationMessageFor(model=>model.ActivityGroupID_FK,"dddddddddd") %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜