开发者

Validate partialview with complex model?

I have a timesheet application where I load a PartialView with jQuery. Everything works fine, but I have no idea how to validate the input. I have tried to do it similarly to how I've done it before, but it doesn't work:

    <% for (int i = 0; i &开发者_开发问答lt; Model.Tasks.Count; i++)
       {
           var task = Model.Tasks[i];
    %>
    <tr class="taskrow">
        <td class="customer">
            <%: task.Customer.CustomerName %>
        </td>
        <td class="task">
            <%: task.TaskName %>
        </td>
        <% for (int j = 0; j < task.TimeSegmentList.Count; j++)
           { %>
        <td>
            <%: Html.TextBoxFor(model => model.Tasks[i].TimeSegmentList[j].Hours, new { @class = "hourInput" })%>
            <%: Html.ValidationMessageFor(model => model.Tasks[i].TimeSegmentList[j].Hours)%>
        </td>
        <% } %>
    </tr>
    <% } %>

Although this PartialView is loaded using jQuery, it also contains a submit button which submits to an action method.

Because I'm using the Entity Framework I have read that I need to decorate the model with DataAnnotations like this:

[MetadataType(typeof(TimeSegmentMetaData))]
public partial class TimeSegment
{

    public class TimeSegmentMetaData
    {
        [Range(0,24,ErrorMessage = "Must be between 0 and 24 hours")]
        public object Hours { get; set; }
    }
}

So I want to make sure it's a number between 0 and 24 entered here for Hours. (I would also like to make sure it's an int, but I haven't gotten to that yet, need to make validation work at all first)

So this doesn't work, what am I doing wrong? Is it not possible to do this because I have the complex model with the for loop in the PartialView?

I was also thinking of trying to find some sort of strict jQuery validation (I've seen jQuery plugins exist for this), but I can't figure out how to use jQuery within the PartialView. Because how can I get jQuery to run when the document.ready function is within the main (parent) view? I would need this anyway, because later I want to be able to do things if a user selects an input field...

PS: I'm still rather new to both jQuery and MVC, so I'd really appreciate clear pointers as to what I'm doing wrong... Thanks!


I would start by changing the type to an Int. Also, you can use foreach instead of the For loop

foreach (Task task in task.TimeSegmentList)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜